使用 std::vector 时抽象类类型"Shape"的新表达式无效错误



所以我有一个Shape抽象基类。

class Shape{
    virtual int getRadius() = 0;
};

和一个派生类Sphere

class Sphere: public Shape {
private:
    int radius;
    int origin = 5;
public:
    Sphere(int radius){
        this->radius = radius;
    }
    int getRadius() {
        return this->radius;
    }
};

在我实例化了一个半径为2的球体对象后,我将其推到一个std::vector对象中。但当我尝试这样做时,我遇到了一个错误:

int main() {
    std::vector<std::shared_ptr<Shape>> shapes;
    Sphere * firstSphere = new Sphere(2);
    shapes.push_back(firstSphere);
    cout << shapes[0]->getRadius() <<endl;
    return 0;
}

在复制构造函数"std::vector&lt_Tp,_Alloc>::vector(const std::vector<_Tp,_Alloc>&)':我想做的是实现多态性,因为我将有几个从shapeABC派生的形状类,我希望能够将它们推送到shape向量容器中,并能够访问它们并调用它们的方法。

我做错了什么?最好的方法是什么?这个问题的要点也是询问实现多态性的最佳方式。

斯克纳里奥:1.形状ABC2.球体形状3.衍生自Shape 的其他类别

对我来说,哪个容器存储Shape派生类的对象(或指针)既高效又简单?

在编写shapes.push_back(firstSphere)时,会将Sphere*隐式转换为shared_ptr<Shape>。但是您试图在shared_ptr上调用的构造函数标记为explicit:

template< class Y > 
explicit shared_ptr( Y* ptr );

因此出现了错误。

有很多方法可以确保显式调用构造函数:

// explicitly calls constructor internally
shapes.emplace_back(firstSphere);
// just explicitly call it yourself
shapes.push_back(std::shared_ptr<Shape>(firstSphere)); 
// just avoid firstSphere altogether
shapes.push_back(std::make_shared<Sphere>(2)); 

最新更新