Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 受保护成员与重载运算符冲突_C++_Class_Inheritance_Protected - Fatal编程技术网

C++ 受保护成员与重载运算符冲突

C++ 受保护成员与重载运算符冲突,c++,class,inheritance,protected,C++,Class,Inheritance,Protected,我有以下课程: class Base { protected: int myint; }; class Derived : public Base { public: bool operator==(Base &obj) { if(myint == obj.myint) return true; else return false; } }; 但当我编译它时,它会出

我有以下课程:

class Base {
protected:
    int myint;        
};

class Derived : public Base {
public:
    bool operator==(Base &obj) {
        if(myint == obj.myint)
            return true;
        else
            return false;
    }
};
但当我编译它时,它会出现以下错误:

int Base::myint
在此上下文中受保护


我认为受保护的变量可以从公共继承下的派生类访问。导致此错误的原因是什么?

Derived
只能在
Derived
的所有实例上访问
Base
的受保护成员。但是
obj
不是
Derived
的实例,它是
Base
的实例,因此禁止访问。下面的代码可以编译,因为现在
obj
是一个
派生的

class Derived : public Base {
public:
    bool operator==(const Derived& obj) const {
        return myint == obj.myint;
    }
};

尝试将
operator==
的参数从
Base&
更改为
Derived&
。(或
派生常量&
,如果不需要修改它)