首页 > 解决方案 > 为模板重载 +=?

问题描述

我有一个基类Animal和一个派生类Bird : Animal。我使用一个模板类来存储指向AnimalBird对象的指针向量。我想以这样一种方式重载运算符,以便我可以在, 所以,+=中插入一个新的animal权利,只是为了得到这个想法。Atlasm_length = m_length + 1pages.push_back(animal)

这是我的模板类:

template <class T>
class Atlas2 {
 public:
  int m_length;
  std::list<T> pages;
  Atlas2() { m_length = 0; }
  ~Atlas2() {}
  void adauga(T data);
  T operator+=(const T& data) {
    this->m_length++;
    this->pages.push_back(data);
    return *this;
  };
};

这是Animal/Bird类:

class Animal {
 protected:
  std::string m_name;

 public:
  Animal() {}
  Animal(std::string name) : m_name{name} {}
  virtual void set_name(std::string name) { m_name = name; }
  virtual std::string get_name() { return m_name; }
  virtual std::string regn() const { return "???"; }

  virtual ~Animal() { cout << "Destructor animal" << '\n'; }
};

class Bird : public Animal {
 public:
  bird() : animal() {}
  bird(std::string name) : Animal{name} {}
  void set_name(std::string nume) { m_name = nume; }

  std::string get_name() { return m_name; }

  std::string regn() const override { return "pasare"; }
  ~bird() { cout << "destructor pasare" << '\n'; }
};

但是,我无法弄清楚这一点。当我像这样使用重载+=运算符时main()

Pasare *c = new Pasare{"vulture"};
Atlas2<Animal *> Atlas;
Atlas += c;    

它向我显示了一个错误,它无法转换Atlas<Animal *><Animal*>.

我应该如何正确实施?任何提示?

注意:模板工作正常,我可以在我的列表中存储指向任何问题AnimalBirds没有问题的指针,并访问它们的特定方法。我只是无法弄清楚这+=部分。

标签: c++classtemplatesoperator-overloadingoverloading

解决方案


Atlas2<T> &你不应该返回T

Atlas2<T>& operator+=(const T& data) {
    this->m_length++;
    this->pagini.push_back(data);
    return *this;
};

推荐阅读