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

查看:35
本文介绍了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();
}

他们以某种方式共享这个指令向量.我关心的是我执行执行"功能的部分.它会起作用吗?它会保留其 Add 类型吗?

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;

存储值,而不是引用.这意味着,无论你如何处理,除了那里的那个 Instruction 对象,它会在未来的某个时候被复制.

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.

此外,由于您使用 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天全站免登陆