2012-07-01 34 views
3
#include <iostream> 

using namespace std; 

struct info { 
    info(int x, int y) : x(x), y(y) {} 
    int x; 
    int y; 
}; 

ostream& operator<<(ostream& out, const info &myinfo){ 
    out << myinfo.x << " " << myinfo.y; 
    return cout; 
} 

int main() { 
    info a(1,2); 
    info b(3,4); 
    cout << a << " " << b << endl; 
} 

即使錯誤超載operator <<上述程序的輸出似乎很好。超負荷返回值<<

誰能告訴我這個重載問題的效果是什麼?我知道重載函數應該返回out而不是cout,但上述版本的行爲如何?

+2

與運算符重載無關,但是您在構造函數中存在一個錯誤: struct info {int x,int y):x(x),y​​(y){} //這裏改爲x ,b更改爲y int x; int y; }; – CapelliC

+0

哈哈。是的,只是一個錯字 – user1494533

回答

1

很明顯,它會在這種情況下工作,因爲目標流是cout。它會在其他情況下破裂。

+0

你能舉個例子嗎? – user1494533

+0

@ user1494533:任何時候你都不會流到'cout'!嘗試使用'cerr'或者'std :: stringstream'來代替。 –

6

在這種情況下,由於您正將std::cout傳遞給超載的operator<<,因此行爲沒有區別。一般情況下,雖然,你將導致" " << b << std::endl來送送std:cout,而你的a會去任何你在通過

例如:

info a(1,2); 
info b(3,4); 
std::ostringstream ss; 
ss << a << " " << b << std::endl; 

會導致ass

+0

感謝你的榜樣! – user1494533

1

它只是發生在這裏工作,因爲outcout指的是同一個對象。