问题
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?
回答1:
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));
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.
回答2:
Pointers!
Declaration:
map<int, element*> elementMap;
Use:
elasticFrame3d thing = elasticFrame3d(1,1);
elementMap[0] = &thing;
来源:https://stackoverflow.com/questions/25465224/making-a-map-in-which-the-value-type-is-an-abstract-class-in-c