c++ - 无法访问类 'A' 中声明的 protected 成员

标签 c++ oop

<分区>

这是我在我的一门 OOP 类(class)的示例中找到的一段代码。当我尝试编译它时,出现以下错误:

'A::x' : cannot access protected member declared in class 'A'.

因为继承,B 不应该能够访问 A 的 protected int 吗?

#include<iostream>
using namespace std;

class A
{
protected: int x;
public: A(int i = -16) { x = i; }
        virtual A f(A a) { return x + a.x; }
        void afisare() { cout << x; }
};

class B : public A
{
public: B(int i = 3) :A(i) {}
        A f(A a) { return x + a.x + 1; }
};

int main()
{
    A *p1 = new B, *p2 = new A, *p3 = new A(p1->f(*p2));
    p3->afisare();
    system("Pause");
}

最佳答案

B 可以访问 A 的成员 x 但只能访问它继承的成员。它无法访问 A 的另一个实例的成员 x(f 中的 a.x)。

关于c++ - 无法访问类 'A' 中声明的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32380414/

相关文章:

c++ - 宏和成员函数冲突

c++ - 如何获取C++11参数包中的类型?

java - 为什么构造函数在java中不被继承?

java - 如果我们无法泛化方法参数,我们是否需要接口(interface)/契约

javascript - 类模拟中的 JS 和方法

performance - Perl - OOP/Moose - 方法签名

C++ 将二进制数组转换为类

c++ - cout char* 打印地址而不是值

c++ - 实现具有迭代器支持的通用固定大小数组

python - 如何在 python 中使用继承将多个对象连接成一个对象? (在运行时)