- 创建基类指针,用派生类赋值的时候,基类的构造函数也会执行。先执行派生类构造函数,再执行基类构造函数,并且指针指向基类函数的派生类部分。
#include<iostream>
using namespace std;
class A{
public:
A(){}
virtual void func()
{
cout<<"A::func"<<endl;
}
virtual void fund()
{
cout<<"A::fund"<<endl;
}
void fun()
{
cout<<"A::fun"<<endl;
}
};
class B:public A{
public:
B(){func();}
void fun(){func();}
};
class C:public B{
public:
C(){}
void func()
{
cout<<"C::func"<<endl;
}
void fund()
{
cout<<"C::fund"<<endl;
}
};
int main(){
A* pa=new B();
pa->fun();
B* pb=new C();
pb->fun();
return 0;
}
- 结果