开发者

Inheritance from macros in Qt4

Part of my code looks something like this.

#include <QObject>
#define MYMACRO : public QObject
#define SIGNAL_MACRO Q_OBJECT signals: void testSignal(std::string s);
#define EMIT_MACRO emit testsignal(s);

class myclass MYMACRO
{
   SIGNAL_MACRO
...

void myclass::method()
{
   std::string s("string");
   EMIT_MACRO
}开发者_如何学编程

If I write the contents of the macros to where they should be expanded it works fine. But if I keep the macros and let the preprocessor do the job then I get an 'undefined reference to myclass::testSignal(std::string)'. I don't understand what's the difference. The preprocessor should expand the macros as they are first encountered, exactly as if I'd written them out myself. I thought I could write anything in a macro and it will simply be copy-pasted to where it's needed.


I think the problem here might be that the Qt meta-object compiler is run before the C++ pre-processor, so it doesn't get to see the Q_OBJECT inside the SIGNAL_MACRO. From the Qt Reference Documentation:

The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.

My advice is, don't do it this way.


Are you sure that when you 'write the contents of the macros' manually, that you are writing code that is exactly the same as that produced by expansion of the macros?

It looks to me that the SIGNAL_MACRO declares the testSignal() function, but does not define it, i.e. function has no body, which would certainly result in the error you are seeing.

However, it is hard to tell from your code, because the use of macros is makes things confusing. I would kindly advise you not to use macros in this way, because it makes the code very hard to read and understand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜