我有一个相当简单的数据结构,它是接口(interface)的一部分。因此,该结构的基类也是一个不定义任何数据的接口(interface)。
该结构可能有不同的数据实现,但它们都必须可以相互分配。这是问题的简化 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
。在您的情况下,通过 other
从 ThingInterface
之外的任何地方访问 GetValue()
都是非法的。 Clang 有一个很好的错误消息,可能更有意义:
note: can only access this member on an object of type '
ThingImplementation
'virtual int GetValue() const = 0; ^
关于c++ - 无法在赋值运算符中访问基类的 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57571969/