如何使用链表重载运算符<<
How to overload operator << with linked list?
对于类,我正在尝试重载<<运算符,以便我可以打印出我创建的对象。 我声明并添加了此内容
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;
}
}
如果要重载类 WORD 的<<,参数必须是"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;
}
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板