c++ - 无法访问的继承公共(public)属性(property)

标签 c++

<分区>

我尝试用一​​些类制作一个基本的 C++ 程序,但遇到了问题。该程序如下所示:

#include<iostream>
using namespace std;

class A {
public:
    int i;
    A(int ai) {this->i = ai;}
    A() {}
};

class B : A {
public:
    A aa;
    B(A &a) : A(a.i) {
        aa = a;
    }
};

int main()
{
    A a(5);
    B b(a);

    cout << "Hello World!" << b.i;
    return 0;
}

程序编译失败:

In function 'int main()':
Line 6: error: 'int A::i' is inaccessible
compilation terminated due to -Wfatal-errors.

但是变量i 在类A 中是公开的。我做错了什么?

最佳答案

您正在私下继承A:

class B : A {
       ^^^^^^

您需要公开继承A:

class B : public A {
       ^^^^^^^^^^^^^

关于c++ - 无法访问的继承公共(public)属性(property),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31478824/

相关文章:

c++ - 检查矩阵是否为上三角 (c++)

c++ - g++,创建用于分发的静态库

c++ - 关于 unique_ptr 的表现

c++ - 将一个类的默认值初始化为另一个c++

c++ - 计算 C++ 的随机数

c++ - 自由类型错误 : FT_Load_Char returns 36

c++ - 结构转换为原始字符问题

c++ - GoF 装饰器模式在 C++ 中使用静态多态性(模板)

c++ - 如何使用引用,避免 header 膨胀和延迟初始化?

c++ - 宏 C++ #define Examples(obje) (::f(s, (obje), arg1, arg2, arg3))