【问题标题】:How to overload operator << with linked list?如何用链表重载运算符<<?
【发布时间】:2012-06-09 01:49:35
【问题描述】:

对于类,我试图重载

WORD you; //this is a linked list that contains 'y' 'o' 'u'

我想这样做

cout << you; //error: no operator "<<" matches theses operands

我必须将插入运算符重载为友元函数,并通过链接打印一个单词。

我已经声明并定义了重载函数,但它仍然不起作用。这是类声明文件,后面是带有函数的.cpp文件

#include <iostream>

using namespace std;
#pragma once

class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};

class WORD
{
public:
WORD(); //front of list initially set to Null
//WORD(const WORD& other);
bool IsEmpty(); //done
int Length();
void Add(char); //done
void Print(); //dont
//void Insert(WORD bword, int position);
//WORD operator=(const string& other);

friend ostream & operator<<(ostream & out, alpha_numeric *front);//******************<-----------------

private:
alpha_numeric *front; //points to the front node of a list
int length;

}; 

在 .cpp 文件中,我将 *front 放在参数中,因为它说 front 在我尝试在函数内使用时未定义,即使我在类中声明了它。然后我尝试了这个。我不知道它是否正确。

ostream & operator<<(ostream & out, alpha_numeric *front)
{
alpha_numeric *p;
for(p = front; p != 0; p = p -> next)
{
    out << p -> symbol << endl;
}
}

【问题讨论】:

  • 你为什么不创建ostream&amp; operator&lt;&lt;(ostream &amp;out, WORD &amp;word)
  • @SevaTitov 它必须作为朋友功能实现,它在作业指导中

标签: c++ linked-list operator-overloading


【解决方案1】:

如果要为WORD类重载

class WORD
{
friend ostream & operator<<(ostream & out, const WORD& w);
}

ostream & operator<<(ostream & out, const WORD& w)
{
alpha_numeric *p;
for(p = w.front; p != 0; p = p -> next)
    out << p -> symbol;
out<<endl;
return out;
}

【讨论】:

  • 你能解释一下为什么它必须是 const 吗?
  • @MikeGordon 你不想在操作符
  • 感谢@JsDoITao 的解决方案,我对此内容还有其他问题。如果 symbol 和 next in-class alpha_numeric 等成员是私有的而不是公有的,我们如何处理它们?我也是 C++ 新手,我遇到了这个问题,但是在类 alpha_numeric 符号中,下一个是私有成员,我给出了符号错误,下一个在这个内容中是私有的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 2013-11-17
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 2011-12-03
相关资源
最近更新 更多