受保护的成员与重载运算符发生冲突 [英] Protected member conflict with overloading operator
本文介绍了受保护的成员与重载运算符发生冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
class Base {
protected:
int myint;
};
class Derived : public Base {
public:
bool operator==(Base &obj) {
if(myint == obj.myint)
return true;
else
return false;
}
};
但是当我编译它时,会出现以下错误:
But when I compile it, it gives the following errors:
int Base :: myint
在此上下文中受保护
我认为可以在公共继承下从派生类访问受保护的变量。造成此错误的原因是什么?
I thought that protected variables are accessible from the derived class under a public inheritance. What is causing this error?
推荐答案
派生
可以访问受保护的成员仅在所有派生的
实例上,基本
。但是 obj
不是 Derived
的实例,它是 Base $的实例c $ c>-因此禁止访问。由于现在
obj
是 Derived
Derived
can access protected members of Base
on all instances of Derived
only. But obj
isn't an instance of Derived
, it's an instance of Base
- so access is forbidden. The following would compile fine, since now obj
is a Derived
class Derived : public Base {
public:
bool operator==(const Derived& obj) const {
return myint == obj.myint;
}
};
这篇关于受保护的成员与重载运算符发生冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文