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

Overloading << operator in template linked list with inheritance

本文关键字:链表 运算符 继承 重载      更新时间:2023-10-16

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

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

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

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

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

评论中的问题:

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

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