继承期间无法访问的基础

Shobhit Tewari

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

    #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)) ===|
来自莫斯科的弗拉德

派生类只能访问其自己的基类子对象的公共或受保护的数据成员。

在这种情况下

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

该对象c2不是派生类的子对象。因此,在操作员内部您可能无法访问其受保护的数据。

通过以下方式更改操作员

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章