Qt reflection mechanism three to obtain information related to classes

1. The member functions of the QMetaObject class to obtain class-related information are:

const char* className() const;
Get the name of the class. Note that if a subclass of QObject does not start the meta-object system (that is, the Q_OBJECT
macro is not used ), then this function will get the closest started meta-object of the class The name of the parent class of the system is no longer returned
. Therefore, it is recommended that all QObject subclasses use the Q_OBJECT macro.
const QMetaObject* superClass() const;
//Returns the meta object of the parent class, or 0 if there is no such object.
 bool inherits(const QMetaObject* mo) const; (Qt5.7)
//If the class inherits from the type described by mo, it returns true, otherwise it returns false. Classes are considered to inherit from themselves.

2. The member functions of the QObject class to obtain class-related information are

 bool inherits(const char* className) const;
//If the class is a subclass of the class specified by className, return true, otherwise return false. Classes are considered to inherit from themselves.

#ifndef M_H //要使用元对象系统,需在头文件中定义类。
#define M_H
#include<QObject>
class A:public QObject{ Q_OBJECT};
class B:public A{ Q_OBJECT};
class C:public QObject{Q_OBJECT};
class D:public C{};
#endif // M_H
//源文件m.cpp 的内容
#include "m.h"
#include <QMetaMethod>
#include <iostream>
using namespace std;
int main()
{ A ma; B mb; C mc; D md;
const QMetaObject *pa=ma.metaObject();
const QMetaObject *pb=mb.metaObject();
cout<<pa->className()<<endl; //输出类名A
//使用QMetaObject::inherits()函数判断继承关系。
cout<<pa->inherits(pa)<<endl; //输出1,类被认为是自身的子类
cout<<pa->inherits(pb)<<endl; //输出0,由pb 所描述的类B 不是类A 的子类。
cout<<pb->inherits(pa)<<endl; //输出1,由pa 所描述的类A 是类B 的子类。
//使用QObject::inherits()函数判断继承关系。
cout<<ma.inherits("B")<<endl; //输出0,类A 不是类B 的子类。
cout<<ma.inherits("A")<<endl; //输出1,类被认为是自身的子类
cout<<md.inherits("D")<<endl; //输出0,因为类D 未启动元对象系统。
cout<<md.inherits("C")<<endl; /*输出1,虽然类D 未启动元对象系统,但类C 已启动,此种情形下
能正确判断继承关系。*/
cout<<md.metaObject()->className()<<endl; /*输出C,此处未输出D,因为类D 未启动元对象系统,
与类D 最接近的启动了元对象系统的父类是C,因此返回C。*/
return 0; 
}

 

Guess you like

Origin blog.csdn.net/weixin_41882459/article/details/114027270