我正在跟踪代码(我删除了一些不重要的代码):

class State {
public:

  virtual void enter() = 0;
  virtual void update() = 0;
  virtual void exit() = 0;
};

class SimpleState : public State {
public:

  SimpleState() = default;
  SimpleState(const SimpleState&) = default;
  SimpleState(SimpleState&&) = default;
  virtual ~SimpleState() = default;

public:

  void enter() override;
  void update() override;
  void exit() override;

public:

  SimpleState& operator=(const SimpleState&) = default;
  SimpleState& operator=(SimpleState&&) = default;
};

由于定义了析构函数,因此我还添加了默认运算符,以解决准则警告,并且还需要定义其他内容(如果记得的话,规则为5)。

如果我通过启用cpp核心准则使用Visual Studio 2019构建它,则会收到以下警告:
SimpleState.hpp: warning C26456: Operator 'SimpleState::operator=' hides a non-virtual operator 'State::operator=' (c.128).
SimpleState.hpp: warning C26456: Operator 'SimpleState::operator=' hides a non-virtual operator 'State::operator=' (c.128).

我想摆脱它,所以我通过以下方式更改了代码:
class State {
public:

  virtual void enter() = 0;
  virtual void update() = 0;
  virtual void exit() = 0;

public:

  virtual State& operator=(const State&) = 0;
  virtual State& operator=(State&&) = 0;
};

class SimpleState : public State {
public:

  SimpleState() = default;
  SimpleState(const SimpleState&) = default;
  SimpleState(SimpleState&&) = default;
  virtual ~SimpleState() = default;

public:

  void enter() override;
  void update() override;
  void exit() override;

public:

  SimpleState& operator=(const SimpleState&) override = default;
  SimpleState& operator=(SimpleState&&) override = default;
};

但是在那种情况下,我得到以下错误:
SimpleState.hpp: error C3668: 'SimpleState::operator =': method with override specifier 'override' did not override any base class methods
SimpleState.hpp: error C3668: 'SimpleState::operator =': method with override specifier 'override' did not override any base class methods

我在做错什么,如何删除准则警告?

最佳答案

我怀疑这种情况下的C26456警告是一个错误,另请参见https://developercommunityapi.westus.cloudapp.azure.com/content/problem/617702/c26456-false-positive-with-operator-in-derived-cla.htmlhttps://developercommunity.visualstudio.com/content/problem/228085/c-core-check-false-positive-c26434.html

所引用的核心准则子句C.128仅适用于虚拟成员函数,但是operator=在您的基类中不是虚拟的,并且与派生类中的签名也不相同,因此没有理由应用它。

确保您确实需要SimpleState中的析构函数声明。您在基类State中具有虚函数,这似乎表明您想多态使用State,并且对象可能是通过State指针而不是SimpleState指针破坏的。在这种情况下,State需要声明一个虚拟析构函数,而不是SimpleState

如果在State中声明虚拟析构函数,则无需在SimpleState中声明任何析构函数,这将从State继承虚拟析构函数。然后SimpleState可以遵循零规则,并且不需要声明的任何复制/移动赋值运算符和复制/移动构造函数,这是首选方法。

关于c++ - 运算符(operator)继承和cpp核心准则c.128的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60205956/

10-11 11:41