#include <iostream.h>
class B
{
private:
virtual void foo() { cout << "B::foo" << endl;}
friend struct A;
};
class D : public B
{
private:
virtual void foo() { cout << "D::foo" << endl;}
};
struct A
{
static void test()
{
D d;
B* pb = &d;
pb->foo();
}
};
void main()
{
struct A m;
m.test();
}
本文通过一个 C++ 示例介绍了如何使用虚函数实现多态,并展示了类之间的友元关系如何帮助跨类访问私有成员。示例中定义了基类 B 和派生类 D,以及一个友元结构 A,用于调用不同类中的 foo 方法。

440

被折叠的 条评论
为什么被折叠?



