本文介绍了向量的虚拟类:是指针干净的方式去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:
这几乎与此条目重复:

我需要创建一个虚拟类的向量。这里的想法:

I need to create a vector of virtual classes. Here the idea:

#include <vector>
using namespace std;

class VirtualFoo {
protected:
    VirtualFoo();
    virtual ~VirtualFoo();
public:
    virtual void doStuff()=0;
};

class ConcreteFoo: public VirtualFoo {
public:
    ConcreteFoo(double a);
    virtual ~ConcreteFoo();
    void doStuff();
private:
    double a;
};

class Foo {
public:
    Foo(std::vector<VirtualFoo> foos);
    virtual ~Foo();
    void doAllStuff();
protected:
    std::vector<VirtualFoo> foos;
};

我想使用这种方式:

int main(int argc, char *argv[]){

    std::vector<ConcreteFoo> cfoos;
    cfoos.push_back(ConcreteFoo(1.0));
    cfoos.push_back(ConcreteFoo(2.0));

    Foo foo = Foo(cfoos);
    foo.doAllStuff();

}

当然这不起作用,因为cfoos是一个向量

Of course this does not work because cfoos is a vector of VirtualFoo and not ConcreteFoo.

现在,如果我不使用VirtualFoo的向量,而是使用VirtualFoo *的向量,并将指针推回到ConcreteFoo的实例,似乎工作罚款。

Now, if I do not use a vector of VirtualFoo but a vector of VirtualFoo* and push back pointers to instances of ConcreteFoo, that seems to work fine.

只是,我不知道这是最干净的方式。这更像是我没有想到任何其他方式这样做。

Just, I am not sure it is the cleanest way to go. It's more like I did not think of any other way of doing this. Is doing this ok ?

推荐答案

具有 std :: vector< VirtualFoo *> cfoos; 很好。您不能实例化抽象类,因此编译器无法实例化或专门化使用抽象类作为值的向量模板。使用基类指针指向元素是很好的,这是Liskov替换原则()

The vector with pointers of std::vector<VirtualFoo*> cfoos; is fine. You cannot instantiate abstract classes, hence the compiler fails to instantiate or specialize vector template that use abstract class as value. Pointing elements with base class pointers is fine which is Liskov substitution principle(http://en.wikipedia.org/wiki/Liskov_substitution_principle)

我同意其他人的意见,共享指针是更好的解决方案,所以你不必担心内存管理: p>

I agree with the comments from others that shared pointers is better solution so that you don't have to worry about memory management:

std::vector<shared_ptr<VirtualFoo>> cfoos;  
cfoos.push_back( shared_ptr<VirtualFoo> (new ConcreteFoo(1.0)) );   
cfoos.push_back( shared_ptr<VirtualFoo> (new ConcreteFoo(2.0)) );

这篇关于向量的虚拟类:是指针干净的方式去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:55