向量和多态性在C ++ [英] Vectors and polymorphism in C++

查看:154
本文介绍了向量和多态性在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个棘手的情况。它的简化形式是这样的

I have a tricky situation. Its simplified form is something like this

class Instruction
{
public:
    virtual void execute() {  }
};

class Add: public Instruction
{
private:
    int a;
    int b;
    int c;
public:
    Add(int x, int y, int z) {a=x;b=y;c=z;}
    void execute() { a = b + c;  }
};

然后在一个类中我做类似...

And then in one class I do something like...

void some_method()
{
    vector<Instruction> v;
    Instruction* i = new Add(1,2,3)
    v.push_back(*i);
}

在另一个类...

void some_other_method()
{
    Instruction ins = v.back();
    ins.execute();
}

他们分享这个说明向量。我关心的是我做执行功能的部分。它会工作吗?它会保留其添​​加类型吗?

And they share this Instruction vector somehow. My concern is the part where I do "execute" function. Will it work? Will it retain its Add type?

推荐答案

不,它不会。

vector<Instruction> ins;

存储值,而不是引用。这意味着,无论你如何,但在那里的指令对象,它将被复制在未来的某个时候。

stores values, not references. This means that no matter how you but that Instruction object in there, it'll be copied at some point in the future.

此外, code> new ,上面的代码泄漏了该对象。如果你想正确地做这件事,你必须做

Furthermore, since you're allocating with new, the above code leaks that object. If you want to do this properly, you'll have to do

vector<Instruction*> ins

或更好:

vector< std::reference_wrapper<Instruction> > ins

我喜欢这个此博客帖子以解释 reference_wrapper

此行为称为物件切片

这篇关于向量和多态性在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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