复试C++14真题 看程序写结果5 虚函数、继承
#include <iostream> using namespace std; class A{ public: virtual void print() {cout<<"A::print"<<endl;} //void print() {cout<<"A::print"<<endl;} }; class B: public A { public: void print() {cout<<"B::print"<<endl;} }; class C: public B{ public: void print() {cout<<"C::print"<<endl;} }; int main(){ B b; C c; A* a; a = &b; a->print(); //B::print a = &c; a->print(); //C::print }
如果是另一种
#include <iostream> using namespace std; class A{ public: //virtual void print() {cout<<"A::print"<<endl;} void print() {cout<<"A::print"<<endl;} }; class B: public A { public: void print() {cout<<"B::print"<<endl;} }; class C: public B{ public: void print() {cout<<"C::print"<<endl;} }; int main(){ B b; C c; A* a; a = &b; a->print(); //A::print a = &c; a->print(); //A::print return 0; }
一定要注意父类与子类的同名函数是否为虚函数。因为没有注意到是虚函数,第一次做的时候就做错了。
标签:易错,14,真题,void,复试,print,public,函数 From: https://www.cnblogs.com/uacs2024/p/18085843