#include
using namespace std;
class Base{
int a, b;
public:
Base(int x, int y) { a = x; b = y; }
void show() { cout << a << ',' << b << endl; }
};
class Derived :public Base {
int c, d;
public:
Derived(int x, int y, int z, int m) :Base(x, y) { c = z; d = m; }
void show() { cout << c << ',' << d << endl; }
};
int main()
{
Base B1(50, 50), * pb;
Derived D1(10, 20, 30, 40);
pb = &D1;
pb->show();
return 0;
}
这是因为在程序中,指针 pb 是一个类型为 Base 的指针,指向的是对象 D1。在调用 pb->show() 时,实际上调用的是基类 Base 中的 show 函数。由于派生类 Derived 中的 show 函数并没有覆盖基类的 show 函数,因此输出的是基类中的 a 和 b 的值,即 10 和 20。