码迷,mamicode.com
首页 > 编程语言 > 详细

C++ RTTI

时间:2019-11-16 23:31:27      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:子类   ==   name   lock   rtu   main   mic   父类   obj   

RTTI(Run-Time Type Identification)运行时类型识别,类似JAVA中的多态

父类接口类:

class Person {
public:
   virtual void eat()=0;
   virtual void run()=0;
};

子类实现

//继承并实现
class Teacher : public Person {
public:
   void Study();
   virtual void eat();
   virtual void run();
};
class Student : public Person {
public:
   void play();
   virtual void eat();
   virtual void run();
};
//.cpp 实现
void Teacher::run() {
   cout << "Teacher::run()" << endl;
}
void Teacher::eat() {
   cout << "Teacher::eat()" << endl;
}
void Teacher::Study() {
   cout << "Teacher::Study()" << endl;
}
void Student::run() {
   cout << "Student::run()" << endl;
}
void Student::eat() {
   cout << "Student::eat()" << endl;
}
void Student::play() {
   cout << "Student::play()" << endl;
}
void Test(Person *obj) {
   cout << typeid(*obj).name() << endl;
   obj->run();
   if (typeid(*obj) == typeid(Student)) {
       Student *student = dynamic_cast<Student *>(obj);
       student->play();
   }
   if (typeid(*obj) == typeid(Teacher)) {
       Teacher *teacher = dynamic_cast<Teacher *>(obj);
       teacher->Study();
   }
   obj->eat();
}
int main() {
   Student student;
   Test(&student);
   return 0;
}

结果:

7Student
Student::run()
Student::play()
Student::eat()

类型转换:

如果子类必须含有虚函数,否则不是多态,其次,必须事引用和指针才能类型转换
如下:

//父类去掉纯虚函数
class Person {
public:
   void eat();
   void run();
};
//子类没有虚函数
class Student : public Person {
public:
   void play();
   void eat();
   void run();
};
int main() {
   Person *person = new Student();
   //子类必须含有虚函数,否则不是多态。其次,必须是引用和指针才能类型转换
   Student *s = dynamic_cast<Student *>(person); //直接报错,错误原因是:person 不是多态类型
   return 0;
}

C++ RTTI

标签:子类   ==   name   lock   rtu   main   mic   父类   obj   

原文地址:https://www.cnblogs.com/wuyanzu/p/11874266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!