問題描述
我是一名 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模板網!