无法在赋值运算符中访问基类的受保护方法
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; ^
相关文章:
- 继承和友元函数,从基类访问受保护的成员
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 基类中受保护的纯虚函数如何被基类的友元类使用?
- 派生类无法访问基类的受保护成员
- 无法在赋值运算符中访问基类的受保护方法
- 为什么我无法使用受保护/私有继承访问派生实例中基类的受保护成员?
- 使用基类的C++和修改私有/受保护的属性
- 使从一个基类派生的类能够使用继承的受保护成员
- 无法访问派生类函数内的基类的受保护数据成员
- 派生类如何使用基类的受保护成员
- 如何影响派生类中受保护的基变量
- 访问基类的受保护成员
- 使用指向派生类中的基类的指针访问受基类保护的成员
- 用受保护的继承指向基类方法
- 如何从另一个类的基类访问派生类中的受保护成员
- 在派生的C 类中,访问基类受保护成员作为公共的访问声明
- C++受保护:无法从派生类中访问基的受保护成员
- c++错误:基函数受保护
- 可以从派生类中的静态函数访问基类受保护的成员吗?
- 使用派生类构造函数填充基类受保护成员