Sas*_*yal 2 c++ oop polymorphism vector c++11
所以我有一个Shape抽象基类.
class Shape{
virtual int getRadius() = 0;
};
Run Code Online (Sandbox Code Playgroud)
还有派生类,Sphere
class Sphere: public Shape {
private:
int radius;
int origin = 5;
public:
Sphere(int radius){
this->radius = radius;
}
int getRadius() {
return this->radius;
}
};
Run Code Online (Sandbox Code Playgroud)
在我实例化一个半径为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;
}
Run Code Online (Sandbox Code Playgroud)
在复制构造函数'std :: vector <_Tp,_Alloc> :: vector(const std :: vector <_Tp,_Alloc>&)':我想要做的是实现多态,因为我将有几个派生自的形状类形状 ABC和我希望能够将它们推入形状矢量容器中,并能够访问它们并调用它们的方法.
我究竟做错了什么?什么是最好的方法呢?这个问题的要点还在于提出实现多态的最佳方法.
Scnerario:1.形状 ABC 2. 球体:形状 3.其他类派生自Shape
对于我来说,存储Shape派生类的对象(或指针)对哪个容器有效且简单?
当你写作时shapes.push_back(firstSphere),你隐含地将你转换Sphere*为a shared_ptr<Shape>.但是您要调用的构造函数shared_ptr标记为explicit:
template< class Y >
explicit shared_ptr( Y* ptr );
Run Code Online (Sandbox Code Playgroud)
因此错误.
有许多方法可以确保显式调用构造函数:
// 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));
Run Code Online (Sandbox Code Playgroud)