【发布时间】:2020-02-12 05:49:23
【问题描述】:
我在 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)) ===|
【问题讨论】:
-
std::complex已经存在,所以using namespace std;也可能是问题的根源。 -
display可以访问自己基地的protected成员。它不能访问protected任何complex实例的成员。
标签: c++ inheritance access-control protected