1

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

简而言之,我有一个抽象类和两个继承了他的派生类。如果我使用 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();
  }
}
4

1 回答 1

3

您正在打印指针。使用取消引用运算符打印出该值。

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

另外,请在发布前缩进您的代码!

评论中的问题:

它现在打印数据,但仅用于基类而不是派生类,出于某种原因

因为方法重载是基于表达式的静态类型。因此用 a List<Base>,调用的方法是operator<<(ostream&, const Base&)。尝试a List<Derived>,您的代码将起作用!您需要一个虚函数调用,它在基类的 operator<< 中为您完成工作,以使包含这两种元素的列表工作。

于 2013-01-26T22:53:33.343 回答