c++ - 无法在赋值运算符中访问基类的 protected 方法

标签 c++ inheritance c++17 protected

我有一个相当简单的数据结构,它是接口(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。在您的情况下,通过 otherThingInterface 之外的任何地方访问 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/

相关文章:

c++ - 具有先前模板参数类型的自动返回类型参数的函数类型的模板参数

c++ - 让赋值运算符作用于声明

带有 IUnityContainer 的 WPF MVVM 创建不需要的多个实例

c++ - 将 std::array 转换为 std::vector

c++ - error : no match for 'operator=' . 尝试从基类继承并从基类初始化?

c# - 从抽象类引用继承类

c++ - 超出范围时如何重置多个变量?

c++ - 我如何对 condition_variable::wait 周围的包装器进行单元测试?

c++ - 派生类的内联函数能否覆盖基类的非内联函数?

c++ - 无法在托管 C++ 中使用 new 关键字创建非托管对象