无法在赋值运算符中访问基类的受保护方法

Cannot access base class' protected method in assignment operator

本文关键字:基类 受保护 方法 访问 赋值运算符      更新时间:2023-10-16

我有一个相当简单的数据结构,它是接口的一部分。因此,结构的基类也是一个不定义任何数据的接口。

此结构可能具有不同的数据实现,但它们都必须彼此可分配。这是问题的简化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。在您的情况下,从除ThingInterfaceother以外的任何地方访问GetValue()都是非法的。Clang有一个很好的错误消息,可能更有意义:

注意:只能在类型的对象上访问此成员 'ThingImplementation'

virtual int GetValue() const = 0;
^