我知道 friend
不是继承的。我有类(class) Parent Person Child
。 Parent 和 Person 是彼此的 friend 。 Parent 具有以下 PROTECTED 功能...
class Person
{
friend class Parent;
public:
Parent * parent;
}
class Parent
{
friend class Person;
protected:
virtual void Answer() = 0;
}
class Child : public Parent
{
void Answer()
{
std::cout << "Child!" << endl;
}
}
我的问题是,如果不继承友元,我怎么能有以下...? (Person 有一个指向 Parent 的指针)
Person person;
Child child;
person.parent->Answer();
为什么这个 Child! 的输出,在尝试访问虚函数时不会抛出运行时错误?
我对子函数的实现方式感到困惑,而且程序在运行时没有出错,因为我预计它正在尝试调用父函数的虚拟 Answer 函数。
最佳答案
这里你访问的不是Child::Answer
而是Parent::Answer
,没关系,因为Parent
是你的 friend 。这是一个 Child
对象这一事实对此无关紧要。但是,重要的是在运行时实际调用什么方法。由于 Parent::Answer
是 virtual
,用 Child::Answer
覆盖它意味着不知道 Child< 是什么的调用者
仍然会调用 Child::Answer
,即使通过 Parent
引用或指针访问 Child
(有一个层在运行时解析适当函数的间接寻址)。
你甚至可以在实现 Child
之前编译它,然后链接到这个 .o
文件,把它交给一个 Child
实例,伪装成Parent&
或 Parent*
。 Person
永远不会有机会甚至知道有一个叫做 Child
的东西,但仍然能够“找到”正确的实现。这就是动态绑定(bind)的力量。
关于C++友元继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215004/