program1:class A{ public: void print(){ cout<<”This is A”<<endl;} }; class B:public A{ public: void print(){ cout<<”This is B”<<endl;} }; int main(){ A a; B b; a.print(); b.print(); } 输出: This is AThis is B program2:
int main(){ //main2 A a; B b; A* p1=&a; A* p2=&b; p1->print(); p2->print(); }
输出:
This is A
This is A program3:
class A{ public: virtual void print(){ cout<<”This is A”<<endl;} //现在成了虚函数了 }; class B:public A{ public: void print(){ cout<<”This is B”<<endl;} //这里需要在前面加上关键字virtual吗? }; 输出:
This is AThis is B 干货:
如果子类覆盖的父类的虚函数则父类的指针或引用实际指向子类的对象那通过该指针或引用调用虚函数时,则将调用子类的(虚)函数 如果不是虚函数,则将调用父类的函数
时间: 2024-11-09 05:17:59