Вопрос

I have been looking around QMetaData and QObject calling the className(). I want to replicate this in my own class but I cannot figure out how QT does it. What I mean is, I do the following but it does not output the correct class (ignore any syntax errors):

#include <iostream>

#define CLASS(name)              \
    std::string className() {    \
        return #name;            \     
    }                           

class A {
public:
   CLASS(A) 

   A(){}
   ~A(){}  

   void output() {
       std::cout << className() << std::endl;
   }
};

class B: public A{
public:
   CLASS(B)
   B(){}
   ~B(){}
};

int main() {
   B b;
   b.output();    // This obviously outputs "A" but I would
                  // like it to output "B" from the base class
                  // function
   return 0;
}

How Qt has it is you do not have to add any more code just the Q_OBJECT macro and you can get the className of the derived class from the base class even if the base class has the output function (in Qt I mean the QObject::debugObjectTree()). How does Qt accomplish this effect without adding any extra code to the derived classes (except maybe a macro), where the base class can output the classname of its derived class?

Thanks in advance.

Это было полезно?

Решение

You need dynamic dispatch (i.e. virtual functions in c++) for this.

Just add virtual before std::string className() in your macro:

#define CLASS(name)              \
virtual std::string className() {    \
    return #name;            \     
}  

http://ideone.com/Kr0Sc

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top