![](/img/trans.png)
[英]How to properly overload < operator in a struct to enable use in a set in C++
[英]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
一個x
和y
的兩個參數構造函數:
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:
如果使用命令行:在命令arg的后面添加“ -std = gnu ++ 11”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.