我試圖編寫一些運算符重載函數,特別是<<
運算符將它與自定義類和std::ofstream
對象一起使用,但我在線查找的各種示例中使用的語法有點困惑。例如,讓我們考慮operator<<
超載作爲一個非成員函數一個簡單的自定義類:運算符超載懷疑
#include <fstream>
class Example {
public:
int first;
int second;
};
// I found this kind of operator on the Internet
std::ofstream& operator<< (std::ofstream& out, Example obj) {
out << obj.first << endl << obj.second;
return out;
}
int main() {
Example a={1,2};
std::ofstream out;
out.open("test");
out << a;
out.close();
}
我真的不明白爲什麼它應該返回std::ofstream&
正常工作。我嘗試使用以下運算符:
void operator<< (std::ofstream& out, Example obj) {
out << obj.first << endl << obj.second << endl;
}
它也起作用。我的意思是,不能out << obj;
被解釋爲operator<< (out , obj);
?爲什麼它必須返回一些東西,因爲我傳遞了對std::ofstream
對象的引用?
同樣懷疑出現了,當我試圖寫operator=
過載作爲自定義類的成員函數,如下面
class Custom{
public:
int up;
int down;
Custom& operator= (Custom a) {
up=a.up;
down=a.down;
return *this;
}
};
我用複製交換成語爲賦值運算符的簡單的例子,所以不要太介意操作符的定義,這只是一個例子。同樣,寫
Custom obj1, obj2;
obj1 = obj2;
,因爲我可以解釋obj1 = obj2;
爲obj1.operator=(obj2)
,爲什麼返回類型Custom&
需要,而不是void
?
查看http://stackoverflow.com/questions/4421706/operator-overloading – juanchopanza