C++ Q_COREAPP_STARTUP_函数和静态类成员方法
我需要使用C++ Q_COREAPP_STARTUP_函数和静态类成员方法,c++,qt,qcoreapplication,C++,Qt,Qcoreapplication,我需要使用qRegisterMetaType()注册我的类,并希望使用 我不想在main()中注册它,因为我需要在一个(非静态链接的)库中注册它 我有很多这样的例子,我不想污染根命名空间。编译器不希望有多个同名的方法,我也不希望每次添加新方法时都考虑唯一的方法名 因此,在我的类中使用静态成员方法 但此示例不编译: class MyClass { public: // ... static void registerMetaType(); } 使用.cpp文件中的实现: MyCl
qRegisterMetaType()
注册我的类,并希望使用
我不想在main()
中注册它,因为我需要在一个(非静态链接的)库中注册它
我有很多这样的例子,我不想污染根命名空间。编译器不希望有多个同名的方法,我也不希望每次添加新方法时都考虑唯一的方法名
因此,在我的类中使用静态成员方法
但此示例不编译:
class MyClass {
public:
// ...
static void registerMetaType();
}
使用.cpp文件中的实现:
MyClass::registerMetaType() {}
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
为什么我不能使用静态成员方法?如果这不是解决这个问题的正确方法,那么有什么更好的方法
更新
编译器错误消息:
/path/to/myclass.cpp:183:1: error: no ‘void MyClass::registerMetaType_ctor_function()’ member function declared in class ‘MyClass’
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
^
In file included from /path/to/qt5-5.6.0/include/QtCore/QtGlobal:1:0,
from /path/to/myclass.h:18,
from /path/to/myclass.cpp:15:
/path/to/myclass.cpp:183:1: error: qualified name does not name a class before ‘{’ token
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
^
/path/to/myclass.cpp:183:1: error: invalid type in declaration before ‘;’ token
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
^
/path/to/myclass.cpp:183:1: error: definition of ‘MyClass::registerMetaType_ctor_function_ctor_instance_’ is not in namespace enclosing ‘MyClass’ [-fpermissive]
/path/to/myclass.cpp:183:1: error: ‘static’ may not be used when defining (as opposed to declaring) a static data member [-fpermissive]
/path/to/myclass.cpp:183:1: error: ‘const int MyClass::registerMetaType_ctor_function_ctor_instance_’ is not a static member of ‘class MyClass’
/path/to/myclass.cpp:183:28: error: uninitialized const ‘MyClass::registerMetaType_ctor_function_ctor_instance_’ [-fpermissive]
Q_COREAPP_STARTUP_FUNCTION(MyClass::registerMetaType)
我已报告Qt的功能请求,以添加对成员函数的支持: 看起来问题在于静态成员函数中的
:
和宏的使用
无论如何,克服“污染根命名空间”和重复符号的替代解决方案是使用命名空间:
namespace { // no duplicate symbol across units
namespace detail { // avoid "polluting" global namespace of this .cpp file
void registerMetaTypes() {
qRegisterMetaType(MyClass*);
}
Q_COREAPP_STARTUP_FUNCTION(registerMetaTypes)
} // namespace detail
} // anonymous namespace
你能发布编译器错误吗?也许您需要
Q\u COREAPP\u STARTUP\u函数(&MyClass::registerMetaType)
有编译错误,有没有&
。请参阅我问题中的更新。
namespace { // no duplicate symbol across units
namespace detail { // avoid "polluting" global namespace of this .cpp file
void registerMetaTypes() {
qRegisterMetaType(MyClass*);
}
Q_COREAPP_STARTUP_FUNCTION(registerMetaTypes)
} // namespace detail
} // anonymous namespace