问题描述
class classa {
public:
virtual void foo();
};
class classb : public classa {
public:
virtual void foo() override;
};
void classa::foo()
{
std::cout << "foo from a" << std::endl;
}
void classb::foo()
{
std::cout << "foo from b" << std::endl;
}
int main()
{
std::vector<classa> stuff;
classa a;
classb b;
stuff.push_back(a);
stuff.push_back(b);
stuff[0].foo();
stuff[1].foo();
return 0;
}
我希望上述代码返回
I expected the above code to return
foo from a
foo from b
$ b b
但它返回 foo从
。
我认为这是因为向量存储 classa
但我不知道。
如何获得 b
?
I think this is because the vector stores classa
but I am not sure. How can I get classb:foo()
to be called by b
?
推荐答案
这发生是因为对象切片,你需要保留一个指针向量(最好是智能指针)。
This happens because of object slicing, you'll need to keep a vector of pointers (preferably smart pointers).
我假设 stuff
定义为 std :: vector< classa> stuff;
。
stuff.push_back(b);
被推入向量的对象是 b
- 特别是 classa
部分。所有其他类型的信息丢失。要使其按预期工作,您需要:
the object pushed into the vector is a slice of b
- particulary the classa
part. All other type info is lost. For this to work as expected, you'd need:
std::vector<classa*> stuff;
或类似。现在你的代码的方式,你不能让它工作,因为 stuff [1]
不再是 classb
,但是 classa
。
or similar. The way your code is now, you can't get it to work because stuff[1]
is no longer a classb
, but a classa
.
这篇关于覆盖父类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!