gpt4 book ai didi

c++ - 在Qt中获取父类(super class)中子类的名称

转载 作者:太空狗 更新时间:2023-10-29 21:22:25 28 4
gpt4 key购买 nike

我有一个由两个子类继承的基类。所有三个类都使用 qDebug() 进行一些调试打印,并使用 Q_FUNC_INFO 来识别打印源。问题在于,当从基类打印时,Q_FUNC_INFO 包含基类的名称,因此无法知道该实例代表两个子类中的哪一个。

到目前为止,我想到的最佳解决方案是在基类中使用 QString 变量而不是 Q_FUNC_INFO,并在实例化时为其提供正确的名称。

还有其他更好的解决方案吗?

最佳答案

Are there any other, more preferable solutions?

一般来说,不,没关系。在这种情况下,如果可能的话,您需要将 Q_FUNC_INFO 放入子类中。如果不是,那你就不走运了,但是……请继续阅读。

Qt 内部也使用显式字符串而不是 Q_FUNC_INFO,我相信部分原因。

对于QObjects,您可以使用元对象编译器进行一些内省(introspection)以动态获取真实名称,即:

const char * QMetaObject::className() const

Returns the class name.

const QMetaObject * QObject::metaObject() const [virtual]

Returns a pointer to the meta-object of this object.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have no pointer to an actual object instance but still want to access the meta-object of a class, you can use staticMetaObject.

在处理构造函数时,您也会看一下这个,因为您的评论似乎表明了这一点:

QMetaMethod QMetaObject::constructor(int index) const

Returns the meta-data for the constructor with the given index.

main.cpp

#include <QObject>
#include <QDebug>

class Foo : public QObject
{
Q_OBJECT
public:
virtual void baz() { qDebug() << "Class name:" << metaObject()->className(); }
};

class Bar : public Foo
{
Q_OBJECT
};

#include "main.moc"

int main()
{
Bar bar;
bar.baz();
return 0;
}

输出

moc main.cpp -o main.moc && g++ -Wall -I/usr/include/qt -I/usr/include/ -I/usr/include/qt/QtCore -lQt5Core -fPIC main.cpp && ./a.out

Class name: Bar

注意:如果你想让这个机制在构造函数中工作,简单的答案是你不能。没有什么能真正帮助你。这是由于 C++ 中继承的处理方式。首先,构建了基类,在那个阶段,子类还没有完全构建(严格来说,甚至不是基类),所以如果不明确地确定基类的附加参数,你就无法真正获得更多关于它的信息构造函数。但是,为了这个简单的事情,你会得到一个臃肿的 API。在这种情况下,我建议只将打印放入子类而不是基类。

关于c++ - 在Qt中获取父类(super class)中子类的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677198/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com