C ++重载[]用于包含shared_ptr的std :: list

时间:2016-11-26 00:21:41

标签: c++ list stl shared-ptr

我正在尝试为包含[]的{​​{1}}重置std::vector::operator[]运算符(类似于list)。它需要返回对位置shared_ptr的元素的引用(我已经给出了设计规范)。

indexcar派生自抽象基类truck。 班级vehicle包含dealership

这就是我试图重载std::list<std::shared_ptr<vehicle>> dealershipLot;运算符的方法; []

我尝试使用std::list<std::shared_ptr<vehicle>>& Dealership::operator[](size_t index)获取元素位置的迭代器并使用std::find返回引用,但似乎&(findIter)需要重载std::find才能使用我的列表类型,但我收到错误

==

以下是我的代码的缩短版本:

binary ==: no operator found which takes a left-hand operand of type std::shared_ptr<vehicle> (or there is no acceptable conversion)

如何重载#include <vector> #include <iostream> #include <list> #include <string> #include <algorithm> #include <memory> #include <fstream> using namespace std; class vehicle { protected: string name; public: vehicle(){ name.clear(); } vehicle(string v) : name(v){}; string getName() const { return name; }; virtual void display(ostream&) const = 0; }; class Car : public vehicle { protected: int no; public: Car(){ no = 0; }; Car(string n, int no) : vehicle(n), no(no) {}; std::string getName() const { return name; } int getNo() const{ return no; } void display(ostream& os) const { os << name << " " << no << std::endl; } }; class Truck : public vehicle { protected: int no; int km; public: Truck(){ no = 0; }; Truck(string n, int no, int km) : vehicle(n), no(no), km(km) {}; std::string getName() const { return name; } int getNo() const{ return no; } int getKm() const{ return km; } void display(ostream& os) const { os << name << " " << no << "" << km << std::endl; } }; class Dealership{ string dealershipName; std::list<std::shared_ptr<vehicle>> dealershipLot; public: Dealership(){ dealershipName.clear(); dealershipLot.clear(); }; Dealership(const std::string n); Dealership(const Dealership&); //Copy constructor Dealership& operator=(const Dealership&); //Copy assignment operator Dealership(Dealership&&); //Move constructor Dealership&& operator=(Dealership&&); //Move assignment operator void operator+=(std::shared_ptr<vehicle> veh); //Operator += overload bool operator==(const std::shared_ptr<vehicle> other){ //??? return dealershipName == other->getName(); } std::list<std::shared_ptr<vehicle>>& operator[](size_t index){ //??? /*size_t index = 3; std::list<std::shared_ptr<vehicle>>::iterator findIter = std::find(dealershipLot.begin(), dealershipLot.end(), index); cout << &(findIter) << endl; return &(findIter);*/ } }; int main() { Dealership d1("lot3"); d1 += std::move(std::shared_ptr<vehicle>(new Car("Toyota", 15))); return 0; } 运算符以获取对[]元素的引用?

1 个答案:

答案 0 :(得分:1)

编辑: 对于任何感兴趣的人,我重载了[];

//Operator [] return reference to element at position n
    vehicle& Task::operator[](size_t index){
        std::list<std::shared_ptr<vehicle>>::iterator it = dealershipLot.begin();
        std::advance(it, index);
        return **it;
    }

我创建了一个迭代器,它通过dealershipLot列表index位置前进。然后返回迭代器指向的对象作为引用。