首页 > 解决方案 > 返回 *this 会给出 Weffc++ 警告

问题描述

我在这里有一些代码,我正在使用 -Weffc++ -Wall -Wextra 进行编译。

基本上我有这个片段:

class base
{};

class test : public base
{
public:
    base& operator=(int)
    {
        return *this;
    }
};

我收到警告:warning: 'operator=' should return a reference to '*this' [-Weffc++]。我真的不知道该怎么做这个警告。我已经读到这完全没问题(即返回一个尊重的 this)。

有没有办法让我的编译器满意?

标签: c++c++11g++weffc++

解决方案


将您的代码更改为:

class test : public base
{
public:
     test& operator=(int)
     {
        return *this;
     }
};

每个人都会很高兴,不仅仅是你的编译器。

PS:如果您想了解更多 -Weffc++ 产生的警告是本书中建议的摘录:

有效的 C++:改进程序和设计的 55 种特定方法,Addison–Wesley,1992,(ISBN 0-321-33487-6)。


推荐阅读