我試圖多載cout運算子來列印一個類。
該類由一個整數值和一個指標組成。所以我希望列印一個整數值和一個記憶體地址,但我得到了一個錯誤。我很困惑,因為類本身已經有一個指標并且無法找出問題所在。
編譯器給出“'.'之前的預期主運算式'。代碼多載部分的令牌”錯誤。
#include <iostream>
using namespace std;
class Node{
public:
int Value;
Node* Next;
};
ostream& operator<<(ostream& a, Node& head){
a << "Value " << Node.Value << endl;
a << "To where " << Node.Next << endl;
return a;
}
int main()
{
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head -> Value = 1;
second -> Value = 2;
third -> Value = 3;
head -> Next = second;
second -> Next = third;
third -> Next = NULL;
cout << head;
return 0;
}
uj5u.com熱心網友回復:
首先,一般我們需要為多載的物件添加一個friend宣告operator<<,以便被成為friended的函式可以訪問型別別的私有欄位,如下所示。但是由于您的型別別的兩個資料成員都是public您可以跳過朋友宣告。
二、Node.value應改為head.value如下圖。
三、cout << head應改為cout << *head如下圖:
class Node{
public:
int Value;
Node* Next;
//friend declaration for overloaded operator<< NOTE: Since both the data members are public you can skip this friend declaration
friend std::ostream& operator<<(std::ostream& a, const Node& head);
};
//definition for overloaded operator<<
std::ostream& operator<<(std::ostream& a,const Node& head){
a << "Value " << head.Value << std::endl << "To where " << head.Next;
return a;
}
int main()
{
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head -> Value = 1;
second -> Value = 2;
third -> Value = 3;
head -> Next = second;
second -> Next = third;
third -> Next = NULL;
std::cout << *head;
//don't forget to use delete to free the dynamic memory
}
另外,不要忘記使用delete(何時/需要),以免發生記憶體泄漏。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441486.html
下一篇:我可以在C 中添加可選型別引數嗎
