切片在 C++ 中是什么意思?

What does slicing mean in C++?(切片在 C++ 中是什么意思?)

本文介绍了切片在 C++ 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它在 C++ FAQ 站点中提到——当作为基类对象按值传递时,较大的派生类对象会被切片",切片是什么意思?任何示例来演示?

It is mentioned in C++ FAQ site -- "larger derived class objects get sliced when passed by value as a base class object", what does slicing mean? Any sample to demonstrate?

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

我使用 VSTS 2008 + 本机 C++ 作为我的开发环境.

I am using VSTS 2008 + native C++ as my development environment.

推荐答案

引用 本讲座:

假设类 D 派生自C 类.我们可以将 D 视为 C 类一些额外的数据和方法.在就数据而言,D 拥有所有的数据C 有,而且可能更多.按照方法,D 不能隐藏任何方法C,并且可能有其他方法.在就 C 的现有方法而言,D唯一能做的就是用自己的版本覆盖它们.

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.

如果 x 是 D 类的对象,那么我们可以相对于 C 对 x 进行切片,通过扔掉所有的扩展使 x 成为 D,并且只保留C部分.切片的结果是始终是 C 类的对象.

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.

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

设计原则: 对对象进行切片关于父类 C仍然应该产生一个格式良好的C类的对象.

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

使用警告:即使 D 是 C,你一定要小心.如果你有一个参数类型是 C 和你提供 D 它将被切片,如果你正在按值、指针或参考.请参阅下面的示例.

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.

注意切片 = 操作符,它会使 lh 不一致.此外, operator= 永远不会是虚拟的,这没有意义.例如,假设 A、B 类都是C 类的子类.仅仅因为一个A是C,B是C,不是意味着您可以将 B 对象分配给 A目的.没有运行时类型您无法制作保险箱的信息分配.

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++ 中是什么意思?

基础教程推荐