c++ - 切片在 C++ 中意味着什么?

标签 c++ oop inheritance visual-studio-2008

在 C++ FAQ 站点中提到——“较大的派生类对象在作为基类对象按值传递时被切片”,切片是什么意思?有什么示例可以演示吗?

http://www.parashift.com/c++-faq-lite/value-vs-ref-semantics.html#faq-31.8

我正在使用 VSTS 2008 + native C++ 作为我的开发环境。

最佳答案

引用 this lecture :

Slicing

Suppose that class D is derived from class C. We can think of D as class C with some extra data and methods. In terms of data, D has all the data that C has, and possible more. In terms of methods, D cannot hide any methods of C, and may have additional methods. In terms of existing methods of C, the only thing that D can do is to override them with its own versions.

If x is an object of class D, then we can slice x with respect to C, by throwing away all of the extensions that made x a D, and keeping only the C part. The result of the slicing is always an object of class C.

slicing http://webdocs.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/slides/slice/slide1.gif

Design Principle: Slicing an object with respect to a parent class C should still produce a well-formed object of class C.

Usage Warning: Even though D is-a C, you must be careful. If you have a argument type that is a C and you supply a D it will be sliced if you are doing call by value, pointer, or reference. See the example below.

Note on virtual functions. Their signatures are used to identify which one to execute.

Watch out for the sliced = operator, it can make the lhs inconsistent. Also, the operator= is never virtual, it wouldn't make sense. For example, suppose classes A, B are both subclasses of class C. Just because an A is a C, and a B is a C, it doesn't mean you can assign a B object to an A object. Without run-time type information you cannot make a safe assignment.

关于c++ - 切片在 C++ 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2432683/

相关文章:

c# - 反序列化具有混合值 System.Text.JSON 的 JSON 数组

c++ - 删除二进制文件中的记录?

php - 如何描述 3 个项目之间的石头剪刀布关系?

c# - 数据提供者与存储库

Javascript 类继承,带有 this._super 和正确的 DefineProperty 描述符

vb.net - 是否可以在 VB.NET 中覆盖属性并返回派生类型?

javascript - React,当子类继承并挂载时,父类是否运行生命周期方法?

c++ - 需要有关 VNC 类应用程序中的图 block 缓存机制的建议

c++ - 对C++头文件的基本了解

c++ - QT中如何更新一个窗口?