警告赋值操作符类引用

warning assignment operator class reference

本文关键字:引用 赋值操作符 警告      更新时间:2023-10-16

我有这样的代码:

class ABC{
    public:
        ABC(std::ostream& os) : _os(os) {}
        void operator() (const Stud* course) {
        Stud->print(_os);
        }
        ABC& operator=(const ABC& other); //Declaration of operator=
    private:
        std::ostream& _os;
    };

在我定义赋值操作符之前,我得到了"无法生成赋值操作符"的警告。我想在对象之间赋值,这个类什么都不做,它只是在for_each算法中打印类。

i try write:
ABC& operator=(const ABC& other){
     return *this;
  }

,但仍然得到警告,其他不使用。我如何定义赋值操作符什么都不做。(不使用#pragma warning语句来抑制警告)。

谢谢!

要摆脱关于未使用参数的警告,只需不命名它:

ABC& operator=(const ABC&){
    return *this;
}

编译器不能为你的类生成赋值操作符的原因是它有一个引用变量,而这些变量只能初始化,不能重新赋值。

如果你不需要赋值操作符,而只是为了让编译器满意而添加了一个赋值操作符,你可以声明它为private,然后不提供实现。

你的代码中有几个问题…

 class ABC
 {
    public:
        ABC(std::ostream& os) : _os(os) {}
        void operator() (const Stud* course) 
        {
           //Stud->print(_os);   // you can't use Stud here - this is wrong
           course->print(_os);
        }
        ABC& operator=(const ABC& other); //Declaration of operator=
    private:
        std::ostream& _os;
    };

此外,由于operator()course定义为const Stud*,因此Stud类中的print方法也应定义为const