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;}
结果是一样的;此处考察的知识点是多态,不要误以为在积累中调用就不会调用到子类的函数; 

猜你喜欢

转载自www.cnblogs.com/hujianglang/p/11989986.html
今日推荐