在向量中存储两个不同的类对象 [英] storing two different class objects in a vector

查看:102
本文介绍了在向量中存储两个不同的类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种在两个矢量中存储两个不同类对象的好方法,每个对象在矢量中都有自己的位置,以便以后可以在需要时存储和访问这些对象。

I'm trying to find a good way to store two different class objects within one vector each object having it's own location within the vector, so the objects can be stored and accessed later when needed.

我使用了一个结构,但是随后我将结构所需要的所有内容都存储到了向量中,这不是我想要的,我将举一个例子说明我的意思。

I have used a structure but then I store everything which the structure has to the vector which isn't what I want, I'll give an example of what I mean.

Class A{
   public:
     void changeNumber(int x) {number = x;}
   private:
     int number;
};

Class B{
   public:
     void changeNumber(int x) {number = x;}
   private:
     int number;
};

struct Object{
   A a;
   B b;
};

Class Main{
   public:
     void storeObject(Object ob) {object.push_back(ob);}
   private:
     std::vector<Object> objects; //when an object is passed both A and B objects are stored within the vector in the same location
};

有没有一种方法可以在一个对象中存储两个不同的类对象,但只能在一个对象中传递一个需要存储的时间,所以我在向量中拥有自己的索引?

Is there a way where I can store two different class objects within one object but only pass one at a time to be stored so I has it's own index within the vector?

推荐答案

如果 A B 具有共同的功能,您将仅在矢量的元素上调用这些功能,可以使用所有共同的成员和成员功能,并从中制成基类。然后使 A B 的派生类为 Object

If A and B have common functions and you'll be calling only these on the elements of a vector, you can take all common members and member functions and make a base class out of it. Then make A and B derived class of Object:

class Object
{
public:
    virtual ~Object() = default;

    void changeNumber(int x) { number = x; }

private:
    int number;
};

class A : public Object
{
    // extension of Object
};

class B : public Object
{
    // extension of Object
};

在这种情况下, A 没什么不同来自 B ,因此所有内容都在 Object 中实现。

In this case, A is no different from B, so everything is implemented in Object.

最后,向量将如下所示:

Finally, your vector will look like this:

std::vector<Object*> objects;

这是使用 std :: shared_ptr 将元素从向量中删除或以其他方式破坏后为您释放内存。

And here's more preferred solution with std::shared_ptr which frees the memory for you after the element is removed from the vector or destructed otherwise.

std::vector<std::shared_ptr<Object>> objects;

存储对象:

void storeObject(std::shared_ptr<Object> const& ob)
{
    objects.push_back(ob);
}

// Example calls
Main main;
main.storeObject(std::make_shared<Object>(A())); // store A
main.storeObject(new A()); // logically same as above

main.storeObject(std::make_shared<Object>(B())); // store B
main.storeObject(new B());

boost :: variant 是存储无法使用继承的多种不同类型时,请执行此操作。

boost::variant is the way to go when storing multiple different types on which you cannot use inheritance.

这篇关于在向量中存储两个不同的类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆