c++ - 为模板重载 +=?
问题描述
我有一个基类Animal
和一个派生类Bird : Animal
。我使用一个模板类来存储指向Animal
或Bird
对象的指针向量。我想以这样一种方式重载运算符,以便我可以在, 所以,+=
中插入一个新的animal
权利,只是为了得到这个想法。Atlas
m_length = m_length + 1
pages.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*>
.
我应该如何正确实施?任何提示?
注意:模板工作正常,我可以在我的列表中存储指向任何问题Animal
或Birds
没有问题的指针,并访问它们的特定方法。我只是无法弄清楚这+=
部分。
解决方案
Atlas2<T> &
你不应该返回T
:
Atlas2<T>& operator+=(const T& data) {
this->m_length++;
this->pagini.push_back(data);
return *this;
};
推荐阅读
- java - mapstruct中的映射循环问题
- python-3.x - 如何在 Airflow-MacOS 中写入本地文件路径
- c# - 用常用数据类型替换对象类型 - 类型安全
- c# - BindingList vs List - WinForms 数据绑定
- json - 如何使用 RESTinstance 使用 JSON 发出 GET 请求?
- java - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String com.example.app.users.getEmail()”
- php - PHP - 获取 PDF 标准、isoname、cmyk 元数据
- python - 尝试将列表附加到数据框,并根据 ID 进行匹配
- kubernetes - Kubernetes liveness probe 日志恢复
- android - 使用二维码应用程序进行库存管理