【问题标题】:Cannot access protected member declared in class 'A' [duplicate]无法访问在“A”类中声明的受保护成员 [重复]
【发布时间】:2015-11-29 13:41:59
【问题描述】:

这是我在我的 OOP 课程之一的示例中找到的一段代码。当我尝试编译它时,我收到以下错误:

'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");
}

【问题讨论】:

    标签: c++ oop


    【解决方案1】:

    B 可以访问A 的成员x,但只能访问它继承的成员。它不能访问A 的另一个实例的成员xf 中的a.x)。

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 2012-11-20
      • 1970-01-01
      • 2015-01-30
      • 2020-09-14
      • 2015-02-27
      • 2016-02-29
      • 2012-05-02
      • 2011-09-27
      相关资源
      最近更新 更多