为什么不能使用普通变量进行多态? [英] Why can't I do polymorphism with normal variables?

查看:134
本文介绍了为什么不能使用普通变量进行多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java程序员,最近开始学习C ++.我为某事感到困惑.

I'm a Java programmer and recently started studying C++. I'm confused by something.

我了解在C ++中,要实现多态行为,您必须使用指针或引用.例如,考虑具有已实现方法getArea()的类Shape.它有几个子类,每个子类以不同的方式覆盖getArea().比考虑以下功能:

I understand that in C++, to achieve polymorphic behavior you have to use either pointers or references. For example, consider a class Shape with an implemented method getArea(). It has several subclasses, each overriding getArea() differently. Than consider the following function:

void printArea(Shape* shape){
    cout << shape->getArea();
}

该函数根据指针所指向的具体Shape调用正确的getArea()实现.

The function calls the correct getArea() implementation, based on the concrete Shape the pointer points to.

工作原理相同:

void printArea(Shape& shape){
    cout << shape.getArea();
}

但是,以下方法不适用于多态性:

However, the following method does not work polymorphicaly:

void printArea(Shape shape){
    cout << shape.getArea();
}

无论在函数中传递哪种具体的Shape,都调用相同的getArea()实现:Shape中的默认实现.

Doesn't matter what concrete kind of Shape is passed in the function, the same getArea() implementation is called: the default one in Shape.

我想了解其背后的技术原因.为什么多态性适用于指针和引用,但不适用于普通变量? (而且我认为这不仅对于函数参数,而且对于任何事物都是如此.)

I want to understand the technical reasoning behind this. Why does polymorphism work with pointers and references, but not with normal variables? (And I suppose this is true not only for function parameters, but for anything).

请解释此行为的技术原因,以帮助我理解.

Please explain the technical reasons for this behavior, to help me understand.

推荐答案

答案是复制语义.

在C ++中按值传递对象时,例如printArea(Shape shape)是您传递的对象的副本.而且,如果将派生类传递给此函数,则复制的所有内容都是基类Shape.如果您考虑一下,编译器将无法执行其他任何操作.

When you pass an object by value in C++, e.g. printArea(Shape shape) a copy is made of the object you pass. And if you pass a derived class to this function, all that's copied is the base class Shape. If you think about it, there's no way the compiler could do anything else.

Shape shapeCopy = circle;

shapeCopy被声明为Shape,而不是Circle,因此编译器可以做的就是构造对象的Shape部分的副本.

shapeCopy was declared as a Shape, not a Circle, so all the compiler can do is construct a copy of the Shape part of the object.

这篇关于为什么不能使用普通变量进行多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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