c++ - 继承期间无法访问的基础
问题描述
我在用 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)) ===|
解决方案
派生类只能访问其自己的基类子对象的公共或受保护数据成员。
在这种情况下
display operator +(complex &c2){
display c3=this->a+c2.a;
return c3;
}
该对象c2
不是派生类的子对象。因此,在运营商内部,您可能无法访问其受保护的数据。
按以下方式更改运算符
display operator +( const display &c2){
return this->a + c2.a;
}
推荐阅读
- laravel - Laravel:使用自动填充 created_at 和 updated_at 插入多条记录
- angular - 角 URL HTTP 请求
- python - 函数可以直接在python中的字典中执行,而不是只在字典中调用函数吗?
- ios - 如何在 SwiftUI 中以交互方式按年份过滤日期列表
- ios - pdf文件未使用目标c显示ios中uiwebview中的所有页面
- c# - C# 存储库模式?复杂的查询仍然放在存储库中?
- vue.js - 在 Vuetify.js 插件中使用 vuex 状态
- system-verilog - 如何使随机重做直到得到我想要的数字?
- spring-boot - 在 Spring Boot 2.3 中找不到 javax.validation
- node.js - Mongoose findOne 查询未定义的值(数据库中不存在)。我正在使用 MERN 进行 Instagram 克隆