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