c++ - 尽管有友元,但无法访问基类

标签 c++ inheritance friend

关于这个错误有很多问题,所有的答案似乎都暗示向下转型是不可能的。只有this answer提到友元作为可能的解决方案,至少据我所知。但是,以下代码(为清楚起见删除了不相关的内容)无法编译:

class C;

class A {
    friend class C;  // this does not help
};

class B : protected A {
    friend class C;  // this does not help either
};

class C {
    public:
    void foo(A* a) {};
};

B b;
C c;

void bar()
{
    c.foo(&b);  // this produces error: class A is an inaccessible base of B
}

为什么友元对引用不起作用?毕竟,“C”完全有能力通过指向“B”的指针调用“A”的 protected 方法。

完整的错误是

prog.cc: In function 'void bar()':
prog.cc:20:13: error: 'A' is an inaccessible base of 'B'
   20 |     c.foo(&b);

最佳答案

你的代码等同于:

B b;
C c;
A * a = &b; // <- This cast produces the error
c.foo(a);

您不能将 &b 转换为 A*,因为无论 C 的友元如何,基类都受到保护。

关于c++ - 尽管有友元,但无法访问基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56673706/

相关文章:

C++ - 派生类是否继承基类的静态成员?

C++ - 必须在头文件中定义友元函数吗?

c++ - VS2003 添加 "additional incl. dirs"后也找不到.h文件

C++ 类方法前向声明

c++ - Cocos2dx 如何计算毫秒数?

c++ - boolean : Incorrect output of cout not 0 or 1

c++ - 如何导出从 Visual Studio 中显式实例化的模板派生的类?

inheritance - F# 添加多个调用基类构造函数的构造函数重载

C++ 私有(private)嵌套抽象类

c++ - 无法将函数定义与 cpp 中的现有声明相匹配