繁体   English   中英

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

[英]How to properly overload '+' operator for a struct

我想为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之前,您不能在非静态非常量成员上具有初始化程序。 如果要将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;
}

或者,给wector一个xy的两个参数构造函数:

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. 添加“ -std = gnu ++ 11”

如果使用命令行:在命令arg的后面添加“ -std = gnu ++ 11”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM