-2
我有以下程序:重載=操作者在C++中使用浮點參數
#include <iostream>
using namespace std;
class N {
public:
float x;
N(){ x = 3.0; }
N(float y){ x = y; }
N &operator=(float f){ return *new N(f); }
};
int main(){
N a;
a = 2.0;
cout << a.x;
return 0;
}
我期待爲得到的結果是2(因爲操作者=定義的),而是它給我3(如沒有行a = 2.0)。請有人解釋我爲什麼發生這種情況,'operator ='的定義有什麼問題?謝謝...
爲什麼要退給'*新的N(F)'的參考? 'operator ='應該返回'* this' ...並且,您在任務運算符中不會更改任何內容**。爲什麼你會期望這個工作? – 2015-03-03 12:01:23
複製賦值運算符用於分配*'this' *,您不應該創建另一個對象。 – 2015-03-03 12:03:17
你需要一個[圖書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list),並學習一些基礎知識。 – 2015-03-03 12:03:47