• 6117阅读
  • 3回复

[提问]求助Qt中如何实现类似instanceof的功能 [复制链接]

上一主题 下一主题
离线xyqlgpp
 
只看楼主 倒序阅读 楼主  发表于: 2011-04-20
在java里面,如果Class Son是Class Father的子类,那么假如创建了一个Son s的实例,那么可以用instanceof运算符来知道s是不是Son类或者Father类的实例。

C++里面,没有instanceof这个运算符。查下了貌似也没有类似instanceof功能的函数。
QT里面的话,貌似可以通过继承QObject来得到类似功能,小弟不才···继承自QObject后,代码一直报错。
所以求助大家了。
代码如下,伪代码部分就是测试s是不是Son或者Father的实例的,不会写,求补完。

  1. class Father {
  2. public:
  3. Father(){fatherInt =2;}
  4. int fatherInt;
  5. };
  6. class Son:public Father{
  7. public:
  8. Son(){sonInt = 1;}
  9. int sonInt;
  10. };
  11. int main(int argc, char *argv[])
  12. {
  13. QApplication a(argc, argv);
  14. MainWindow w;
  15. w.show();
  16. Son *s = new Son();
  17. qDebug()<<s->fatherInt;
  18. if (s是Son类的实例){
  19. qDebug()<<"S is instance of Class Son";
  20. }
  21. if (s是Father类的实例){
  22. qDebug()<<"S is instance of Class Father";
  23. }
  24. return a.exec();
  25. }
离线asalei

只看该作者 1楼 发表于: 2011-04-20
inherits
离线asalei

只看该作者 2楼 发表于: 2011-04-20
QObject::inherits
离线xyqlgpp
只看该作者 3楼 发表于: 2011-04-20
回 2楼(asalei) 的帖子
你好,我觉得是我使用的方法不对,请指正下。代码如下,qDebug()<<"SisinstanceofClassSon";qDebug()<<"SisinstanceofClassFather";两个语句都没有输出。

  1. #include <QtGui/QApplication>
  2. #include "mainwindow.h"
  3. #include <QList>
  4. #include <QDebug>
  5. class Father :public QObject{
  6. public:
  7.     Father(){fatherInt =2;}
  8.     int fatherInt;
  9. };
  10. class Son:public Father{
  11. public:
  12.     Son(){sonInt = 1;}
  13.     int sonInt;
  14. };
  15. int main(int argc, char *argv[])
  16. {
  17.     QApplication a(argc, argv);
  18.     MainWindow w;
  19.     w.show();
  20.     Son *s = new Son();
  21.     qDebug()<<s->fatherInt;
  22.     if (s->inherits("Son")){
  23.         qDebug()<<"S is instance of Class Son";
  24.     }
  25.     if (s->inherits("Father")){
  26.         qDebug()<<"S is instance of Class Father";
  27.     }
  28.     return a.exec();
  29. }

[ 此帖被xyqlgpp在2011-04-20 18:14重新编辑 ]
快速回复
限100 字节
 
上一个 下一个