Protected member conflict with overloading operator

痴心易碎 提交于 2019-12-10 05:18:21

问题


I have the following classes:

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 is protected within this context

I thought that protected variables are accessible from the derived class under a public inheritance. What is causing this error?


回答1:


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;
    }
};


来源:https://stackoverflow.com/questions/29879275/protected-member-conflict-with-overloading-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!