多态不能发生在父类的构造方法中

来源:互联网 发布:2016宏观经济数据分析 编辑:程序博客网 时间:2024/06/08 06:55
#include "stdafx.h"#include <iostream>using namespace std;class Father{public:    Father(){        dosomething();    }    void getMove(){        dosomething();    }    virtual void dosomething(){        cout << "This is Father." << endl;    }};class Son :public Father{public:    Son(){}    void dosomething(){        cout << "This is Son." << endl;    }};int _tmain(int argc, _TCHAR* argv[]){    Father *f = new Son;    f->getMove();    return 0;}

输出:
This is Father
This is Son
在创建子类对象的时候,会首先调用父类的构造方法,此时子类还没有构造出来,所以多态还不能实现,具体如代码所示。

0 0