可能重复:
C++ 中的公共虚函数派生私有
class B
{
private:
int b;
public:
B(int i);
virtual void show()
{
cout<<"B::show()called. "<<b<<endl;
}
};
B::B(int i=0)
{
b=i;
}
class D:public B
{
private:
int d;
void show()
{
cout<<"D::show() called. "<<d<<endl;
}
public:
D(int i, int j);
};
D::D(int i=0, int j=0):B(i)
{
d=j;
}
void fun(B&obj)
{
obj.show();
}
/*if I redefine fun() as follow, the result would be the same
void fun(B*obj)
{
obj->show();
}
*/
int main()
{
D *pd=new D(5,8);
fun(*pd); //K
delete pd;
}
程序的输出是“D::show() called.”,表示调用了类 D 的私有部分中声明的虚函数。你不觉得很奇怪吗?如何从外部访问类的私有成员?