为什么我不能对普通变量进行多态?

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

问题描述

限时送ChatGPT账号..

我是一名 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,所以编译器所能做的就是构造一个 的副本对象的形状部分.

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.

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