我试图重载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;
}
首先,通常我们需要为重载的operator<<
添加一个好友声明以便be 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
(在需要的时候/地方(,这样就不会发生内存泄漏。