C++ 多态例子


测试一道题:



#include <iostream>

using namespace std;

class Parent
{
public:
    Parent(){}
    virtual void doit(){ cout << "this is parent" << endl;}
    virtual void printOut() { doit();}
    void printOut1(){doit();cout << "printOut1" << endl;}
};

class Son : public Parent
{
public:
    Son(){}
    void doit() { cout << "this is son" << endl;}
    void printOut() {doit(); cout << "this is son a " << endl;}
};

int main(int argc, char *argv[])
{
    Parent* p = new Son();
    p->doit();
    p->printOut();
    p->printOut1();
    return 0;
}

输出结果:
this is son
this is son
this is son a
this is son
printOut1

如果:
void printOut1(){doit();cout << "printOut1" << endl;}
改为:
void printOut1(){this->doit();cout << "printOut1" << endl;}
结果是一样的;此处考察的知识点是多态,不要误以为在积累中调用就不会调用到子类的函数; 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM