【问题标题】:Overloading << operator in template linked list with inheritance使用继承重载模板链表中的 << 运算符
【发布时间】:2013-01-10 14:58:13
【问题描述】:

我正在尝试在模板链表中重载

简而言之,我有一个抽象类和两个继承他的派生类。 如果我使用 dynamic_cast,所有 3 个类都有运算符

但是当我尝试在模板链表中使用运算符

抽象类 - 播放器

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

【问题讨论】:

  • 我只是希望你的代码实际上没有像那样缩进。
  • 这里不是我这样出来的

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


【解决方案1】:

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

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

还请在发布前缩进您的代码!

评论中的问题:

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

因为方法重载是基于表达式的静态类型。因此使用List&lt;Base&gt;,调用的方法是operator&lt;&lt;(ostream&amp;, const Base&amp;)。试试List&lt;Derived&gt;,你的代码就可以工作了!您需要一个虚函数调用,该调用在基类的 operator

【讨论】:

  • 下次我会注意缩进的!它现在打印数据,但仅用于基类而不是派生类,出于某种原因我编辑了原始问题 - 添加了输出
  • 嘿,还是不行,还有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 2011-12-05
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多