Ste*_*ski 5 c++ inheritance class protected
我有以下课程:
class Base {
protected:
int myint;
};
class Derived : public Base {
public:
bool operator==(Base &obj) {
if(myint == obj.myint)
return true;
else
return false;
}
};
Run Code Online (Sandbox Code Playgroud)
但是当我编译它时,它会出现以下错误:
int Base::myint在这种情况下受到保护
我认为受保护的变量可以在公共继承下从派生类访问.导致此错误的原因是什么?
Derived可以访问仅Base在所有实例上的受保护成员Derived.但obj它不是一个实例Derived,它是一个实例Base- 因此禁止访问.以下编译正常,因为现在obj是一个Derived
class Derived : public Base {
public:
bool operator==(const Derived& obj) const {
return myint == obj.myint;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
496 次 |
| 最近记录: |