[英]How do I print a strucure in c++?
我們可以使用structure.element
來打印結構的元素。 但是我想一次打印一個完整的結構。
是否有類似cout<<strucutre
的方法,就像我們可以在Python中打印列表或元組一樣。
這就是我要的:
struct node {
int next;
string data;
};
main()
{
node n;
cout<<n;
}
是。 您應該為對象cout
覆蓋<<操作符。 但是cout
是ostream類的對象,因此您不能只是簡單地對該類重載<<操作符。 您必須使用朋友功能。 函數主體將如下所示:
friend ostream& operator<< (ostream & in, const node& n){
in << "(" << n.next << "," << n.data << ")" << endl;
return in;
}
如果您的班級中有私人數據,則該函數為friend。
您需要正確地重載<<操作符:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.