重载<<带有继承的模板链表中的运算符

时间:2013-01-26 22:32:11

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

我正在尝试重载<<模板链表中的运算符。

简而言之,我有一个抽象类和2个派生类来引导他。 所有3个类都有运算符<<书面和如果我使用dynamic_cast,那么效果很好。

但是当我尝试使用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);

&lt;&lt;&lt;&lt;&lt;基地和运营商派生工作做得好!只有当我尝试在模板链表中使用它时,我才能得到地址而不是数据:

模板关联列表

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();
  }
}

1 个答案:

答案 0 :(得分:3)

您正在打印指针。使用dereference运算符打印出值。

output<<*(Nd.m_data)<<endl;

另请在发布前缩进代码!

评论中的问题:

  

它现在打印数据但仅出于基类而不是出于某种原因导出的类

因为方法重载基于表达式的静态类型。因此,使用List<Base>时,调用的方法为operator<<(ostream&, const Base&)。试试List<Derived>,你的代码就可以了!您需要一个虚拟函数调用,它可以在运算符中为您工作&lt;&lt;基类的制作包含两种元素的列表。