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

Cannot access base class' protected method in assignment operator

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

这个结构可能有不同的数据实现,但它们都必须可以相互赋值。这是问题的简化 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;
                 ^~~~~~~~

我以为可以访问 class' protected 基础成员。这是怎么回事?

在此代码段中:

void operator=(const ThingInterface& other) override { value = other.GetValue(); }

protected 仅适用于此处的 this。在您的情况下,从 ThingInterfaceother 以外的任何地方访问 GetValue() 都是非法的。 Clang 有一个很好的错误消息,可能更有意义:

note: can only access this member on an object of type 'ThingImplementation'

virtual int GetValue() const = 0;
            ^