2011-09-19 42 views
3

我遇到函數,而不是重載操作< <與COUT使用,聲明一個函數,它接受一個ostream並返回一個ostream聲明一個接受和返回「ostream&」而不是重載operator <<的函數有什麼用?

例子:

#include <iostream> 

class A { 
private: 
    int number; 
public: 
    A(int n) : number(n) {} 
    ~A() {} 
    std::ostream& print(std::ostream& os) const; 
    friend std::ostream& operator<<(std::ostream& os, const A a); 
}; 

實施的例子:

std::ostream& A::print(std::ostream& os) const { 
    os << "number " << number; 
    return os; 
} 

std::ostream& operator<<(std::ostream& os, const A a) { 
    os << "number " << a.number; 
    return os; 
} 

現在,如果我跑這我可以在不同情況下使用不同的功能,例如..

int main() { 
    A a(1); 

    std::cout << "Object."; a.print(std::cout); 
    std::cout << "\n\n"; 
    std::cout << "Object." << a; 
    std::cout << "\n\n"; 

    return 0; 
} 

輸出:

Object.number 1 

Object.number 1 

似乎沒有要在那裏將需要打印功能,因爲你只能單獨或在「COUT鏈」的開始使用,但從來沒有的情況在它的中間或末尾,這可能使它無用。不是(如果找不到其他用途)最好使用「void print()」函數嗎?

+0

使用是真的讓我煩惱。我看不到任何有效的理由。 –

+0

這不完全正確。你可以嵌套函數而不是鏈接它。 'a.print(std :: cout <<「Object。」);' – mydogisbox

+0

我會非常厭惡'a。在「之後」打印(a.print(std :: cout <<「之前」)<<「之間)」「之後」;「。雖然。 – MSalters

回答

2

這將使很多更有意義,如果operator<<()本來的樣子

std::ostream& operator<<(std::ostream& os, const A a) { 
    return a.print(os); 
} 

然後operator<<()不需要成爲朋友。

+0

謝謝你的代碼示例。這很有道理,你回答一個問題的方式有點奇怪:)如果不是因爲它在「答案」下,我會認爲它更像是對我的例子的評論;) –

7

在繼承層次結構發揮作用的地方是有意義的。您可以使print方法變爲虛擬,並在基類的運算符中委託虛擬方法進行打印。

+0

謝謝。即使認爲它不需要是虛擬的,應該像歐內斯特在其他答案中寫的那樣使用,我理解你的觀點。它幫了很多,謝謝。 –

0

可以用作COUT鏈的開始的功能當然聽起來比一個不能,所有其他條件相同的更有用。

我已經實現了幾個帶有簽名的函數,就像你描述的一樣,因爲operator<<只是一個名字,有時候我需要以多種不同的方式傳輸對象。我有一種格式用於打印到屏幕,另一種格式用於保存文件。對於兩者來說使用<<將是非平凡的,但爲至少一個操作選擇人類可讀的名字是很容易的。

0

使用operator<<假定只有一個明智的方法來打印數據。有時候這是真的。但有時也有多種有效的方式來想輸出數據:

#include <iostream> 
using std::cout; using std::endl; 
int main() 
{ 
    const char* strPtr = "what's my address?"; 
    const void* address = strPtr; 

    // When you stream a pointer, you get the address: 
    cout << "Address: " << address << endl; 

    // Except when you don't: 
    cout << "Not the address: " << strPtr << endl; 
} 

http://codepad.org/ip3OqvYq

在這種情況下,您可以選擇的方式之一爲方式,並有其他功能(print? ) 對於其餘的。或者你可以使用print。 (或者你可能使用流標誌來觸發你想要的行爲,但是這很難建立和使用一致。)

相關問題