2017-06-21 77 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; 
} 

函数是朋友,以防您的类中有私人数据。