c++ - 继承期间无法访问基址

标签 c++ inheritance access-control protected

我在 C++ 中练习继承时遇到错误。我尝试用谷歌搜索,但我很困惑。有人请帮助我。

    #include <iostream>

using namespace std;

class complex{
protected:
    int a;
    complex(int a){
        this->a=a;
    }
    virtual void showData()=0;
};

class display:private complex{
public:
    display(int a=0):complex(a){
    }
    void showData(){
        cout << a << endl;
    }
    display operator +(complex &c2){
        display c3=this->a+c2.a;
        return c3;
    }
};

int main()
{
    display c1=5, c2=7, c3;
    c3=c1+c2;
    c3.showData();
    return 0;
}

我收到的错误是:

In member function 'display display::operator+(complex&)':|
error: 'int complex::a' is protected|
error: within this context|
In function 'int main()':
error: 'complex' is an inaccessible base of 'display'|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

最佳答案

派生类只能访问其基类子对象的公共(public)或 protected 数据成员。

在此背景下

display operator +(complex &c2){
    display c3=this->a+c2.a;
    return c3;
}

对象c2不是派生类的子对象。因此,在运算符(operator)内部您可能无法访问其 protected 数据。

按以下方式更改运算符

display operator +( const display &c2){
    return this->a + c2.a;
}

关于c++ - 继承期间无法访问基址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396501/

相关文章:

c++ - 界面的解决方法

java - 使用抽象类的组合关系-Java

authorization - 基于权限的集合过滤

php - 使用通配符提供访问控制允许来源

c++ - 为什么我应该避免在 C++ 中使用 malloc?

C++读取文件,数组变量矩阵

c++ - 使用 for_each 和 lambda 函数从 vector<int> 中减去一个变量

c++ - 指针非类型模板参数的用途?

javascript - 使用流程运行时在 Javascript 中实现接口(interface)

c++ - 私有(private)枚举访问无法从嵌套类的友元函数编译