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

 

原文链接: https://www.cnblogs.com/hujianglang/p/11989986.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 多态例子

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/307097

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午4:58
下一篇 2023年2月16日 上午4:59

相关推荐