构造函数中无法实现多态

来源:互联网 发布:sql not in() 编辑:程序博客网 时间:2024/06/03 13:55

#include <iostream>  using namespace std;  class Parent  {  public:      Parent()      {          this->printfn();      }      virtual ~Parent(){}      virtual void printfn()      {          cout <<"1 ";      }      void test_again(){printfn();}  };  class Son : public Parent  {  public:      void printfn()      {          cout <<"2 ";      }      Son()      {          printfn();      }      ~Son(){}  };  int main(int argc, char* argv[])  {      Parent* p = new Son();//构造函数中无法实现多态,因为子类对象都没有完全创建成功      p->test_again();//子类已经构造完成        int sign = 1;      //switch中default不是必须的      switch(sign)      {          case 1:cout<<"123"<<endl;break;          case 2:break;      }      return 0;  }  

子类构造时,先会调用父类构造函数,父类构造函数中调用printfn,它是一个虚函数,但是此时子类还处于构造过程中并没有构建完成,因此无法调用派生类的实现,只能调用父类本身的实现,我们看到的就是无法呈现多态了。这里将会输出1 2. 








0 0
原创粉丝点击