创建继承对象的方法

时间:2013-10-21 04:08:21

标签: c++ oop inheritance

快速提问。我有一堆像这样继承的类:

Object_____
  |       |
Actor    Item
  |
  |_______
Human  Animal

我还有一个名为Room的类,定义如下:

class Room 
{
    Object * addObject (unsigned long _UID, string _name);
    map<int, Object *> objects; // A map containing the Objects within the room
}

我想要做的是让函数addObject()能够实例化任何类型的Object类,比如Room.addObject(Object::Actor::Human),然后将人类对象添加到我的对象列表中房间。如果有帮助的话,它们都有相同的构造函数参数。有没有办法在C ++中做到这一点?

2 个答案:

答案 0 :(得分:1)

template<typename T> Object* addObject( ... ) {
  Object* myobject = new T(...);
  objects.insert({someint, myobject});
}

...
myroom.addObject<Human>(...);

您需要将地图从存储对象更改为存储指向对象的指针,并找出对象的所有者是什么,以便您清理它们。 (可能有助于您的地图存储unique_ptrshared_ptr s。

答案 1 :(得分:1)

我认为您正在寻找的是C ++的工厂模式。虽然有许多方法可以用C ++实现工厂,但据我所知,没有标准。

我认为简单通常是最好的,所以这里是一个使用示例代码的非常简单的对象工厂的示例:

#include <memory>
#include <string>
#include <map>
using namespace std;

// Stub class definitions
class Object { public: Object() {} ~Object() {} };
class Actor : public Object { public: Actor() {} ~Actor() {} };
class Human : public Actor { public: Human() {} ~Human() {} };
class Animal : public Actor { public: Animal() {} ~Animal() {} };
class Item : public Object { public: Item() {} ~Item() {} };

class ObjectFactory
{
public:
    static shared_ptr<Object> create_object(string name);
};

shared_ptr<Object> ObjectFactory::create_object(string name)
{
    if (name == "Human")
        return shared_ptr<Object>(new Human());
    if (name == "Actor")
        return shared_ptr<Object>(new Actor());
    if (name == "Animal")
        return shared_ptr<Object>(new Animal());
    if (name == "Item")
        return shared_ptr<Object>(new Item());
    throw "unknown object type";
}

class Room 
{
public:
    shared_ptr<Object> addObject (unsigned long _UID, string _name);
    map<int, shared_ptr<Object>> objects; // A map containing the Objects within the room
};

shared_ptr<Object> Room::addObject(unsigned long _UID, string _name)
{
    shared_ptr<Object> object = ObjectFactory::create_object(_name);
    objects[_UID] = object; // not sure if this is what you intended to use _UID for...
    return object;
}

int main()
{
    Room room;
    room.addObject(1, "Actor");
    return 0;
}

请注意,这可以使用Object *代替shared_ptr<Object>来完成,您只是不会自动引用计数/删除,并且必须自己跟踪对象(不是太多)考虑到它们存储在地图中很难。