继承如何与友元类一起工作?

问题描述 投票:0回答:2

我知道这个主题有很多答案,但我不明白为什么我的代码能正常工作:

class Printer;

struct Base {
    virtual void foo1() = 0;
    virtual void foo2() = 0;
};
class Derived1 : Base
{
private:
    void foo1() override {
        cout << "derived1 calls foo1" << endl;
    }
    friend class Printer;
public:
    void foo2() override {
        cout << "derived1 calls foo2" << endl;
    }
};

struct Derived2 : public Derived1 {
    void foo2() override {
        
        cout << "derived2 calls foo2" << endl;
    }
};
 
struct Printer {
    void print() {
        Derived2* d = new Derived2();
        d->foo1();
        d->foo2();
    }
};

一般代码由一个支持两个纯虚方法的基类型

Base
组成,
Derived1
是继承和实现Base接口的类,它与
Printer
类友好并标记
的实现foo1
是私有的,因此类 Derived2 在从
foo1
继承时无法访问方法
Derived1
。但是在类
Print
的打印方法中,我可以通过指向 Derived2 的指针来使用 Derived1 的两个函数。为什么会这样?会员不是无法访问吗?

附带问题:有没有办法将派生类中的方法标记为“已完成”(即,在从派生类继承的类中,只有它们的覆盖方法不能被覆盖)?

c++ inheritance friend virtual-functions
2个回答
0
投票

为什么会这样?会员不是无法访问吗?

不,你让它可以访问:

  friend class Printer;

毕竟,这就是

friend
声明的作用。这是它在 C++ 中的唯一使命:让其他类可以访问私有类成员,否则其他类将无法访问它们。

附带问题:有没有办法将派生类中的方法标记为 '完成'(即,只有它们的覆盖方法不能被覆盖 从派生类继承的类)?

这听起来像一个

final
说明符。


0
投票

友谊没有被继承。 Printer 类是 Derived1 的友元,因此可以通过 Derived2 类访问 Derived1::foo1()。它是类 Derived2 不能调用 Derived1::foo1() 因为 Derived1::foo1() 是私有的。

© www.soinside.com 2019 - 2024. All rights reserved.