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++ 中的向量和多态性
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
