我有一个抽象类element
和一个子类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;
};
我想要的是制作这样的地图:
map<int, element> elementMap;
但是当我收到此错误时:
error C2259: 'element' : cannot instantiate abstract class
甚至可以这样做吗?如果是的话怎么样?
答案 0 :(得分:3)
由于它具有抽象功能,您无法创建类型element
的值。如果要存储从element
派生的类型的对象,则需要存储适当的指针或对这些对象的引用。例如,您可以使用std::unique_ptr<element>
或std::shared_ptr<element>
(您需要包含#include <memory>
)并在适当的内存区域中分配具体对象。
也就是说,你会使用这样的东西:
std::map<int, std::unique_ptr<element>> elementMap;
elementMap[17] = std::unique_ptr<element>(new elasticFrame3D(3.14, 2.71));
顺便说一下,您使用的是不同的命名约定:使用CamelCase类型时,通常使用大写字母和使用小写首字母的对象编写。
答案 1 :(得分:-1)
指针!
Declaration:
map<int, element*> elementMap;
使用:
elasticFrame3d thing = elasticFrame3d(1,1);
elementMap[0] = &thing;