我有3节课:

class Being : public QObject {
    Q_OBJECT
public:
    explicit Being(QObject *parent = nullptr);
};

class Animal : public Being {
    Q_OBJECT
public:
    explicit Animal(QObject *parent = nullptr);
};

class Dog : public Animal {
    Q_OBJECT
public:
    explicit Dog(QObject *parent = nullptr);
};
存在的实现如下:
Being::Being(QObject *parent) : QObject(parent) {
    qDebug() << staticMetaObject.className();
}
我有以下代码:
Being *pBeing = new Being();
Being *pAnimal = new Animal();
Being *pDog = new Dog();
问题是:有一种方法可以实现Being的构造函数,以便我可以访问指向我的Being基类的实际实例,以便上述代码的日志为:
Being
Animal
Dog

编辑:
我的意图是,我希望能够拥有一个会在Being基类内部进行处理的Animal.txtBeing.txtDoc.txt。而且我需要根据实例的类型知道是否需要解析Animal.txtBeing.txtDoc.txt以获得更多信息。
Qt支持吗?我是否可以使用一种机制来使用C++ / Qt实现此目的?如果没有,是否有任何优雅的折衷解决方案?

最佳答案

Being的构造函数中,这是不可能的,因为尚未构造封闭的对象,因此有关该对象的元数据不可用。但是,您可以编写在构造对象之后应调用的initialize方法,例如具有打印功能:

class Being : public QObject {
    Q_OBJECT
public:
    explicit Being(QObject *parent = nullptr) { qDebug() << this->metaObject()->className(); }  // this will always print "Being"
    void initialize() { qDebug() << this->metaObject()->className(); }  // this will print the actual class name
};

class Animal : public Being {
    Q_OBJECT
public:
    explicit Animal(QObject *parent = nullptr) { initialize(); }  // you can already use this method in the constructor
};

TEST(xxx, yyy)
{
    Being* being = new Being();
    Being* animal = new Animal();
    being->initialize();
    animal->initialize();  // or you can call it later
}
万一initialize方法不是一个好的解决方案,您可以随时通过Being构造函数对其进行破解:explicit Being(QString name, QObject* parent = nullptr;然后是explicit Animal(QObject *parent = nullptr): Being("Animal") {},但是我认为它不太优雅。

09-07 11:08