如何正确重载结构'+'运算符

How to properly overload '+' operator for a struct

本文关键字:运算符 何正确 重载 结构      更新时间:2023-10-16

我想为A struct重载'+'操作符,但我得到编译器警告这是我的尝试:

struct wektor{
    int x;
    int y=0;    
    int norm(){
        return x*x+y*y;
    }
};
wektor& operator +(wektor &a,wektor &b){
    wektor c;
    c.x=a.x+b.x;  // 12 line - warning here
    c.y=a.y+b.y;
    return c;
};

编译器警告:

[警告]非静态数据成员初始化项只能在第12行

中使用-std=c++11或-std=gnu++11[默认启用]

这个警告告诉你一行:

int y=0;

在c++ 11之前,不能在非静态非const成员上使用初始化式。如果你想将y初始化为0,那么你必须为wektor提供一个带有成员初始化列表的构造函数。

尽管如此,您的operator+参数应该是const wektor&类型的。它还应该按值返回,因为此时你返回的是对一个局部对象的引用,它将在函数结束时被销毁,这很糟糕。它应该看起来像这样:

wektor operator +(const wektor &a, const wektor &b){
    wektor c;
    c.x=a.x+b.x;  // 12 line - warning here
    c.y=a.y+b.y;
    return c;
};

首先,二元操作符+应该返回一个新值,而不是一个引用。如果以引用作为输入来实现,则它们应该是const:

wektor operator +(const wektor &a, const wektor &b);
第二,这个警告是关于这个初始化的:
struct wektor{
    int x;
    int y=0;    // HERE! C++11 only
    int norm(){
        return x*x+y*y;
    }
};

只能在c++ 11中这样做。可以在c++ 03中使用构造函数。

struct wektor{
    wector() : y() {} // zero-initializes y
    int x;
    int y;
    int norm(){ return x*x+y*y;}
};

回到operator+,我将实现一个成员operator+=,然后在非成员operator+中使用它:

wektor operator +(wektor a, const wektor &b)
{
  return a+= b;
}

或者,为xy提供wector的两个参数构造函数:

wector(int x, int y) : x(x), y(y) {}

蚂蚁然后

wektor operator + (const wektor& a, const wektor &b)
{
  return wector(a.x + b.x, a.y + b.y);
}

不是那样的。签名应该是

wektor operator +(const wektor &a, const wektor &b)

。不要从+操作符返回引用,更重要的是,不要返回临时的引用。

这是一个警告,说明您正在使用c++ 11中的一个特性,该特性在以前的c++标准中是不可用的。

当你知道你所编写的程序按照你的想法工作时,你就可以通过执行以下命令来消除此错误:

如果你正在使用CodeBlocks:

  1. 右键单击"构建选项…"
  2. 选择"其他选项"选项卡
  3. 添加"化gnu + + 11"

如果你使用命令行:在命令参数中添加"-std=gnu++11"