c++语法(2)
#include<iostream> #include<windows.h> using namespace std; class Parents { public: virtual void vir_func(char a='x',char b='y',char c='z'); //虚函数 Parents(); ~Parents(); }; void Parents::vir_func(char a,char b,char c) { cout<<"父类的vir_func函数正在运行..."<<"参数为:"<<a<<","<<b<<","<<c<<endl; } Parents::Parents() { cout<<"父类的构造函数正在运行..."<<endl; } Parents::~Parents() {} class Child:public Parents { public: ~Child(); Child(int a,char c); }; Child::Child(int i,char c) { cout<<"子类的构造函数正在运行..."<<"参数为:"<<i<<","<<c<<endl; } Child::~Child() {} class B { public: Parents *Par; void Init(); }; void B::Init() { //父类指向子类 Par=new Child(2,'c'); cout<<"基类类型的指针已经绑定到派生类..."<<endl; Par->vir_func('d','e','f'); } int main() { B Test; Test.Init(); system("pause"); return 0; }
#include<iostream> #include<windows.h> using namespace std; class Parents { public: virtual void vir_func(char a='x',char b='y',char c='z'); //虚函数 Parents(); ~Parents(); }; void Parents::vir_func(char a,char b,char c) { cout<<"父类的vir_func函数正在运行..."<<"参数为:"<<a<<","<<b<<","<<c<<endl; } Parents::Parents() { cout<<"父类的构造函数正在运行..."<<endl; } Parents::~Parents() {} class Child:public Parents { public: void vir_func(char a,char b,char c); ~Child(); Child(int a,char c); }; void Child::vir_func(char a,char b,char c) { cout<<"子类的vir_func函数正在运行..."<<"参数为:"<<a<<","<<b<<","<<c<<endl; } Child::Child(int i,char c) { cout<<"子类的构造函数正在运行..."<<"参数为:"<<i<<","<<c<<endl; } Child::~Child() {} class B { public: Parents *Par; void Init(); }; void B::Init() { //父类指向子类 Par=new Child(2,'c'); cout<<"基类类型的指针已经绑定到派生类..."<<endl; Par->vir_func('d','e','f'); } int main() { B Test; Test.Init(); system("pause"); return 0; }
从上面的2段程序可以看出:
当基类动态绑定到派生类时,如果派生类没有实现基类的虚函数,那么调用的是基类自己实现的虚函数。
若派生类重新定义虚函数,那么执行的则是派生类实现的虚函数。