【问题标题】:warning assignment operator class reference警告赋值运算符类参考
【发布时间】:2014-05-21 06:33:36
【问题描述】:

我有这个代码:

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 算法中打印类。

我试着写:

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

但仍会收到其他不使用的警告。 我如何定义赋值运算符什么都不做。 (不使用#pragma 警告语句来抑制警告)。

谢谢!

【问题讨论】:

  • 赋值运算符的主体是在哪里写的?
  • 我写了内联赋值运算符的主体
  • 我也写了这个 ABC& operator=(const ABC& ){ return *this; } 它的工作,但我不知道它是否正常
  • 我明白了,但我不明白为什么要编写一个什么都不做的赋值运算符......它不会分配任何东西,对吧?
  • 因为我需要这个类来完成其他任务,并且没有赋值运算符我会收到警告

标签: c++ class reference warnings


【解决方案1】:

要消除有关未使用参数的警告,请不要命名它:

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

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

如果您不需要赋值运算符,而只是添加一个以使编译器满意,则可以将其声明为private,然后不提供实现。

【讨论】:

    【解决方案2】:

    您的代码中的一些问题...

     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

    除此之外,代码编译得很好。

    【讨论】:

    • 是的,你说得对,我没有复制我的代码,好吧,我写的和你一样,我在 Visual stidio 2008 中检查了这段代码,第 4 级,我收到警告,因为 assigmnet 操作员...
    • 尝试去掉赋值运算符中的格式参数声明——定义ABC& operator=(const ABC&) { return *this;}
    • 另外,你能发布Stud类定义吗?
    猜你喜欢
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2011-11-14
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    相关资源
    最近更新 更多