问题描述
我有一个抽象类element
和一个子类elasticFrame
:
I have an abstract class element
and a child class elasticFrame
:
class element
{
public:
virtual Matrix getStiffness() = 0;
protected:
Matrix K;
};
class elasticFrame3d:public element
{
public:
elasticFrame3d(double E, double G);
virtual Matrix getStiffness();
virtual Matrix getTransform();
private:
double E, G;
};
我想要做的是这样的地图:
what I want is to make a map like this:
map<int, element> elementMap;
但是当我收到此错误时:
but when I get this error:
error C2259: 'element' : cannot instantiate abstract class
是否有可能做到这一点?如果是,怎么办?
is it even possible to do this? if yes how?
推荐答案
您将无法创建类型为element
的值,因为它具有抽象功能.如果要存储从element
派生的类型的对象,则需要存储合适的指针或对这些对象的引用.例如,您可以使用std::unique_ptr<element>
或std::shared_ptr<element>
(您需要包含#include <memory>
)并将具体对象分配到合适的存储区域中.
You won't be able to create a value of type element
as it has abstract function. If you want to store objects of a type derived from element
, you'll need to store a suitable pointer or reference to these objects. You can, e.g., use std::unique_ptr<element>
or std::shared_ptr<element>
(you need to include #include <memory>
) and allocate the concrete objects in a suitable memory area.
也就是说,您将使用以下内容:
That is, you would use something like this:
std::map<int, std::unique_ptr<element>> elementMap;
elementMap[17] = std::unique_ptr<element>(new elasticFrame3D(3.14, 2.71));
顺便说一句,您使用的是一个不常用的命名约定:使用CamelCase时,类型通常使用大写字母,而对象则使用小写首字母.
BTW, you are using an unusal naming convention: when using CamelCase types are normally written with a capital letter and objects using a lowercase initial letter.
这篇关于制作一个地图,其中值类型是C ++中的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!