C++友元继承

标签 c++ inheritance virtual friend

我知道 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::Answervirtual,用 Child::Answer 覆盖它意味着不知道 Child< 是什么的调用者 仍然会调用 Child::Answer,即使通过 Parent 引用或指针访问 Child(有一个层在运行时解析适当函数的间接寻址)。

你甚至可以在实现 Child 之前编译它,然后链接到这个 .o 文件,把它交给一个 Child 实例,伪装成Parent&Parent*Person 永远不会有机会甚至知道有一个叫做 Child 的东西,但仍然能够“找到”正确的实现。这就是动态绑定(bind)的力量。

关于C++友元继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215004/

相关文章:

c++ - 返回 NULL 作为对象时没有收到任何警告

c++ - 使用抽象类的容器来容纳子类

python - 通过类层次结构合并字典类属性

java - 基于参数在父类中使用子类的静态成员

directory - Azure Web 角色中的虚拟目录

c++ - 链接器错误 : DLL and inheritance

python - 如何在 C++ 中使用 ZeroMQ 传送多个图像?

c++ - "Event ID 26 Source Application Popup"之类的错误有何帮助

linux - 当目标 IP 不是分配给接口(interface)的 IP 时,在 TUN/TAP 接口(interface)上接收 IP 数据包

c++ - lld-link错误编译 Chrome 与ffmpeg附加调用