题目
声明并实现f(),使其在基类中是vitual的。
更改main()以执行上述要求和虚拟调用。
代码
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int ii) : i(ii) {}
~A() {}
void f() const {cout << "A::f is created."<< endl;}
};
class B {
int i;
public:
B(int ii) : i(ii) {}
~B() {}
virtual void f() const {cout << "B::f is created."<< endl;}
};
class C : public B {
A a;
public:
C(int ii) : B(ii), a(ii) {}
~C() {}
void f() const {
a.f();
B::f();
}
};
int main() {
C c(47);
B* p = &c ;
p->f();
}
结果
f()在基类B中是虚函数,在派生类C中重写。
以指针的形式调用f(),先调用A类中的f(),然后调用B类中的f()。