如何正确重载结构'+'运算符
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;
};
编译器警告:
中使用-std=c++11或-std=gnu++11[默认启用][警告]非静态数据成员初始化项只能在第12行
这个警告告诉你一行:
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;
}
或者,为x
和y
提供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:
- 右键单击"构建选项…"
- 选择"其他选项"选项卡
- 添加"化gnu + + 11"
如果你使用命令行:在命令参数中添加"-std=gnu++11"
相关文章:
- 如何正确实现和访问运算符的各种自定义枚举器
- 为用户定义的类正确调用复制构造函数/赋值运算符
- C++ 如何正确重载 + 运算符
- 如何在C++中正确重载运算符转换字符*?
- 如何正确使用重载的"运算符<<"?
- 在这里使用删除运算符是否正确,我很困惑
- 如何在 rxcpp 自定义运算符中正确推断泛型
- 我无法让这个虚拟模板化函子运算符返回正确的类型
- 重载加号运算符的正确方法是什么
- 重载全常量类型的复制赋值运算符的正确方法是什么?
- 实现运算符的正确方法!=用于类外的模板作为一个免费函数
- 此代码对于重载比较运算符是否正确
- c++中线程安全索引运算符的正确方法
- C++删除运算符.如何正确使用
- 逗号运算符的正确用法是什么
- 在派生类和切片中使用运算符=的正确方式
- c++中重载二元关系运算符的正确方法
- ->、->* 和 .* 运算符的正确术语是什么?
- 这是逻辑"and"运算符的正确用法吗?
- 这是运算符<</>>的正确实现吗?