[英]Cannot access base class' protected method in assignment operator
我有一個相當簡單的數據結構,它是接口的一部分。 這樣,結構的基類也是一個不定義任何數據的接口。
此結構可能具有不同的數據實現,但是它們都必須可以相互分配。 這是問題的簡化MCVE:
class ThingInterface {
public:
// Assignment operator required from the interface to all derived classes
virtual void operator=(const ThingInterface& other) = 0;
protected:
virtual int GetValue() const = 0;
};
class ThingImplementation : public ThingInterface {
public:
void operator=(const ThingInterface& other) override { value = other.GetValue(); }
protected:
virtual int GetValue() const { return value; }
private:
int value;
};
GetValue
受保護的原因是在我的實際代碼中,該值描述了內部狀態(初始化,未初始化,錯誤...)。 雖然它仍然需要復制。
MSVC錯誤:
error C2248: 'ThingInterface::GetValue': cannot access protected member declared in class 'ThingInterface'
note: see declaration of 'ThingInterface::GetType'
note: see declaration of 'ThingInterface'
在Ideone上看到的錯誤:
prog.cpp: In member function ‘virtual void ThingImplementation::operator=(const ThingInterface&)’:
prog.cpp:11:83: error: ‘virtual int ThingInterface::GetValue() const’ is protected within this context
void operator=(const ThingInterface& other) override { value = other.GetValue(); }
^
prog.cpp:6:17: note: declared protected here
virtual int GetValue() const = 0;
^~~~~~~~
我是不可能訪問基類的protected
成員的。 這里發生了什么?
在此片段中:
void operator=(const ThingInterface& other) override { value = other.GetValue(); }
protected
只適用於this
在這里。 就您而言,從ThingInterface
other
任何地方訪問GetValue()
是非法的。 Clang有一個很好的錯誤消息,可能更有意義:
注意:只能在“
ThingImplementation
”類型的對象上訪問此成員virtual int GetValue() const = 0; ^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.