Vectors and polymorphism in C++(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++ 中的向量和多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中的向量和多态性
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
