Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
问题描述
我是一名 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.
这篇关于为什么我不能对普通变量进行多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能对普通变量进行多态?
				
        
 
            
        基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				