引用和对象切片
我没有随身携带《Effective C++》,这让我很烦恼,我不得不要求自己保持理智。 https://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c
class Foo : public Bar{}
void MyFunc(Bar &_input);
如果我传入一个 Foo,我是否会与
I don't have my Effective C++ with me and this is bugging me so much that I have to ask for my own sanity. Given
class Foo : public Bar{}
void MyFunc(Bar &_input);
If I pass in a Foo
, am I tangling with the slicing problem or have I avoided it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是问题,因为您正在传递引用。您没有创建新对象,只是让 MyFunc 访问原始对象。
Not a problem, because you're passing in a reference. You're not creating a new object, just letting MyFunc access the original object.
由于您要传递引用 - 否,除非您稍后分配给
Bar
的实例。Since you are passing the reference - no, unless you later assign to an instance of
Bar
.仅当将对象强制转换为其父类时,切片才会出现问题。转换指针或引用时不会进行切片。
Slicing is only a problem when you cast an object to its parent class. There is no slicing when you cast pointers or references.