对象切片是否有用? [英] Is object slicing ever useful?

查看:100
本文介绍了对象切片是否有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们将派生类的对象分配或复制到其基类的对象时,会丢失对象的派生部分,从而导致对象切片。

Object slicing happens when we assign or copy an object of derived class to an object of its base class, losing the derived part of it in the process.

已在这里更详细地解释: C ++中的切片问题是什么? a>。

It has been explained in more depth here: What is the slicing problem in C++?.

(Myself,我不认为它是一个问题,而是语言的价值语义的自然结果,但这不是这个问题的要点。)

(Myself, I don't see it as a problem, rather a natural consequence of language's value semantics, but that's not the point of this question.)

我不知道的是:有没有情况下你会使用它?

What I wonder is: are there ever situations where you'd use it purposedly? A situtation where it is the "right tool for the job"?

推荐答案

当然,当想要删除

例如,我们有一个对象系统设置,其中每个基类属于一个派生类型,每个派生类型有各种依赖关系,可能通过依赖注入来实现。可能希望创建一个基类的克隆,虽然可能需要为该基类的实际派生类型创建一组全新的依赖关系。

For example say we have an object system setup where each base belongs to a derived type, and each derived type has various dependencies, perhaps fulfilled through dependency injection. A clone of a base might want to be created, though a completely new set of dependencies for the actual derived type of that base may want to be assigned.

这可以是比如一个游戏引擎,其中有许多类型的碰撞。每个对撞机以各种方式从类似基本接口的对象派生。我们想要克隆一个collider来检索它的位置和缩放(从基础),但是想在这个基础之上放置一个完全不同的派生实现。 对象切片可以是一个简单的方法来实现这一点。

This can be likened to an game engine where there are many types of colliders. Each collider derives from a base interface-like object in various ways. We want to clone a collider to retrieve it's position and scale (from base), but want to place an entirely different derived implementation on-top of this base. "Object slicing" could be a simple way to achieve this.

在现实中,一个组件或聚合对象组织会比对象切片更有意义,但它大多是相同的想法。

In reality a component, or aggregate object organization would make a lot more sense than object slicing specifically, but it's mostly the same idea.

这篇关于对象切片是否有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆