我正在尝试在模板链接列表中重载 << 运算符。
简而言之,我有一个抽象类和两个继承了他的派生类。如果我使用 dynamic_cast,所有 3 个类都有 operator << 编写和运行良好。
但是,当我尝试在模板链接列表中使用运算符 << 时,由于某种原因,我要么得到地址,要么得到链接器错误。
抽象类 - 播放器
#ifndef PLAYER_H_
#define PLAYER_H_
#include <iostream>
class Player {
private:
const char* m_name;
int age;
public:
static int numofPlayers;
Player(const char*,int);
virtual ~Player();
friend std::ostream& operator<<(std::ostream& out, const Player &p);
};
std::ostream& operator<<(std::ostream& out, const Player &p);
#endif
派生类之一
class Goalkeeper:public Player {
private:
int Saved_Goals;
int Shirt_Number;
public:
Goalkeeper(const char* name,int age, int number);
~Goalkeeper();
friend std::ostream& operator<<(std::ostream& out, const Goalkeeper& s);
};
std::ostream& operator<<(std::ostream& out, const Goalkeeper& s);
基础和派生的两个 << 运算符都运行良好!只有当我尝试在模板链表中使用它们时,我才会得到地址而不是数据:
模板链表
template <typename T>
class Node {
T* m_data;
Node* next;
public:
Node ();
Node(T*, Node<T>*);
~Node();
T* getData ()const {return this->m_data;};
Node* getNext()const{return this->next;};
template <typename T>
friend std::ostream& operator<<(std::ostream &output, const Node<T>& Nd );
};
template <typename T>
std::ostream &operator << (std::ostream &output,const Node<T>& Nd ) {
output<<Nd.m_data<<endl;
return output;
}
template <typename T>
void List<T>::PrintMe() const {
Node<T>* temp=this->head;
while(temp) {
cout<<*temp;
temp=temp->getNext();
}
}