看起来像是多态?其实是继承
#include <iostream>using namespace std;class B{private:int nBVal;public:void Print(){cout << "nBVal=" << nBVal << endl;}void Fun(){cout << "B::Fun" << endl;}B(int n) { nBVal = n; }};class D : public B{private:int nDVal;public:void Print(){B::Print();cout << "nDVal=" << nDVal << endl;}void Fun(){cout << "D::Fun" << endl;}D(int n) : B(3 * n) { nDVal = n; }};int main(){B *pb;D *pd;D d(4);d.Fun();pb = new B(2);pd = new D(8);pb->Fun();pd->Fun();pb->Print();pd->Print();pb = &d;pb->Fun();pb->Print();return 0;}
- 一开始我也是想用多态虚函数来做的,但是派生类
D中要么定义一个普通的Print()要么就定义成虚函数,二者不可得兼,不符合重载的条件(参数表不同) - 这个题主要是考察在派生类中如何初始化父类,如何访问父类的成员
