C++ 中的向量和多态性

2023-01-20C/C++开发问题
0

本文介绍了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++ 中的向量和多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6