2017-06-21 456 views
0

我們可以使用structure.element來打印結構的元素。但我想一次打印完整的結構。如何在C++中打印結構?

有沒有類似cout<<strucutre的方法,就像我們可以在Python中打印列表或元組一樣。

這就是我想要的:

struct node { 
    int next; 
    string data; 
}; 

main() 
{ 
    node n; 
    cout<<n; 
} 
+0

重載運算符<< –

+1

一切你想知道:https://stackoverflow.com/questions/4421706/operator-overloading – NathanOliver

+0

你有重載'std :: ostream&Operator <<(std :: ostream&,const node&)'操作符來執行此操作。 –

回答

0

您需要正確重載< <操作:

#include <string> 
#include <iostream> 
struct node { 
    int next; 
    std::string data; 
    friend std::ostream& operator<< (std::ostream& stream, const node& myNode) { 
     stream << "next: " << myNode.next << ", Data: " << myNode.data << std::endl; 
     return stream; 
    } 
}; 

int main(int argc, char** argv) { 
    node n{1, "Hi"}; 

    std::cout << n << std::endl; 
    return 0; 
} 
0

是。您應該覆蓋對象cout的< <運算符。但是cout是類ostream的一個對象,因此您不能只是簡單地重載該類的< <運算符。你必須使用朋友功能。函數體將如下所示:

friend ostream& operator<< (ostream & in, const node& n){ 
    in << "(" << n.next << "," << n.data << ")" << endl; 
    return in; 
} 

函數是朋友,以防您的類中有私人數據。