2017-05-26 47 views
0

在一個使用它的類重載operator<<()功能,它會在main()函數中使用像ostream和reference如何自動創建?

int main() 
{ 
    MyOwnClass myClass; 
    cout << myClass; 

} 

是如何的< <運營商能夠創建ostream的&參考 並且我們可以做到這一點像

operator<<(myClass); 

,因爲它是一個友元函數

+1

'cout << myClass;'僅僅和函數調用'operator <<(cout,myClass)'一樣。你有什麼特別的問題嗎? –

+0

我在想''cout.operator <<(myClass)'''謝謝幫我明確我的想法 – arc

+0

@πάνταῥεῖ理論上,它也可以是一個函數調用'cout.operator <<(myClass)'(儘管當然不是'cout')。 – Walter

回答

1

必須重載輸出流運算符std::ostream& << myclass。二進制運算符(如<<)可以作爲其第一個操作數類型的成員(並將第二個操作數作爲唯一參數)或作爲以兩個操作數爲參數的獨立函數實現。

在這裏,只有第二個選項是可能的,因爲您不能更改std::ostream的定義。例如

struct myclass // just an example 
{ 
    int data; 
}; 

std::ostream& operator<<(std::ostream&os, myclass const&obj) 
{ 
    return os << obj.data; 
} 

函數體內部,這個調用operator<<(std::ostream&, int),這是在iostream定義並返回參照其上輸入端接收的相同ostream。如果是更復雜的課程,則可以返回流。

std::ostream& operator<<(std::ostream&os, myclass const&obj) 
{ 
    for(auto x:obj.table) 
    os << std::setprecision(12) << x 
    return os; 
}