C++ RTTI

419 阅读1分钟

C++RTTI

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;
}