这不是很丧气吗?
如果我这样做,
double d = 34.56;
int i = (int)d;
我不是“沮丧”吗?
或者
这个术语仅用于类和对象吗?
我很困惑,因为在这种情况下,我们从较大的 double
“向下转换”到较小的 int
,但在类的情况下,我们从较小的 “向下转换” >基类
到更大的派生类
。
从某种意义上说,这两个约定不是相反的吗?
If I do
double d = 34.56;
int i = (int)d;
Am I not "downcasting"?
OR
Is this term only used in terms of classes and objects?
I am confused because in this case we are "downcasting" from a bigger double
to a smaller int
, but in case of classes, we "downcast" from a smaller base class
to a bigger derived class
.
Aren't these two conventions, in some sense, opposite?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
http://en.wikipedia.org/wiki/Downcasting
不,你并不沮丧,因为 double 和 int 不是类。
http://en.wikipedia.org/wiki/Downcasting
No, you do not downcast, since double and int are not classes.
不,你没有向下投射。你只是在进行转换,并且你正在删除小数点后的任何内容。
向下转换在这里不适用。基元
int
和double
不是 C++ 中的对象,并且不像类层次结构中的两个对象那样相互关联。它们是独立且原始的实体。向下转换是指将一个对象转换为派生自该对象的另一个对象的行为。它指的是从类层次结构的根向下移动的行为。它与所讨论的类型的大小无关。
No, you are not down casting. You are just casting, and you're chopping off anything after the decimal.
Down casting doesn't apply here. The primitives
int
anddouble
are not objects in C++ and are not related to each other in the way two objects in a class hierarchy are. They are separate and primitive entities.Down casting refers to the act of casting one object into another object that derives from it. It refers to the act of moving down from the root of the class hierarchy. It has nothing to do with the sizes of types in question.
int
和double
都是基元,而不是类,因此类的概念不适用于它们。是的,它是从“较大”类型到“较小”类型的转换(就数值大小而言),但它只是“强制转换”而不是“向下强制转换”
int
anddouble
are both primitives and not classes, so the concepts of classes don't apply to them.Yes, it is a conversion from a "larger" to a "smaller" type (in terms of numerical size), but it's just a "cast" and not a "downcast"
两者并不完全相反,而是完全无关。在示例中,我们采用一种类型的值,并且强制转换采用该值并生成一个类似的值,该值的类型模糊相似,但完全不相关。
在使用诸如
dynamic_cast
之类的东西遍历继承树的情况下,我们将获取一个指向对象的指针(或引用),并且之前决定将其视为指向其他类型对象的指针,我们基本上(试图)再次将其视为(更接近)原始类型的对象。然而,特别是,我们根本没有创建新的或不同的值——我们只是创建相同值(即相同的实际对象)的不同视图。The two aren't so much opposite as simply unrelated. In the example case, we're taking a value of one type, and the cast takes that and produces a similar value of a type that's vaguely similar, but completely unrelated.
In the case of traversing an inheritance tree with something like
dynamic_cast
, we're taking a pointer (or reference) to an object, and having previously decided to treat it as a pointer to some other type of object, we're basically (attempting to) treat it as (something closer to) the original type of object again. In particular, however, we're not creating a new or different value at all -- we're simply creating a different view of the same value (i.e., the same actual object).你不是在选角——你是在转换。完全不同的事情。
You aren't casting -- you're converting. Different thing entirely.