問題描述
我是一名 Java 程序員,最近開始學(xué)習(xí) C++.我被某些事情搞糊涂了.
I'm a Java programmer and recently started studying C++. I'm confused by something.
我知道在 C++ 中,要實(shí)現(xiàn)多態(tài)行為,您必須使用指針或引用.例如,考慮一個(gè)帶有實(shí)現(xiàn)方法 getArea()
的 Shape
類.它有幾個(gè)子類,每個(gè)子類都以不同的方式覆蓋 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();
}
函數(shù)根據(jù)指針指向的具體Shape
調(diào)用正確的getArea()
實(shí)現(xiàn).
The function calls the correct getArea()
implementation, based on the concrete Shape
the pointer points to.
效果相同:
void printArea(Shape& shape){
cout << shape.getArea();
}
但是,以下方法不能多態(tài)地工作:
However, the following method does not work polymorphicaly:
void printArea(Shape shape){
cout << shape.getArea();
}
不管函數(shù)中傳入什么樣的Shape
,都會(huì)調(diào)用相同的getArea()
實(shí)現(xiàn):Shape<中的默認(rèn)實(shí)現(xiàn)/代碼>.
Doesn't matter what concrete kind of Shape
is passed in the function, the same getArea()
implementation is called: the default one in Shape
.
我想了解這背后的技術(shù)推理.為什么多態(tài)適用于指針和引用,而不適用于普通變量?(而且我想這不僅適用于函數(shù)參數(shù),而且適用于任何東西.
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).
請(qǐng)解釋這種行為的技術(shù)原因,以幫助我理解.
Please explain the technical reasons for this behavior, to help me understand.
推薦答案
答案是復(fù)制語義.
當(dāng)您在 C++ 中按值傳遞對(duì)象時(shí),例如printArea(Shape shape)
一個(gè)副本是你傳遞的對(duì)象.如果將派生類傳遞給該函數(shù),則復(fù)制的只是基類 Shape
.仔細(xì)想想,編譯器不可能做任何其他事情.
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
,所以編譯器所能做的就是構(gòu)造一個(gè) 的副本對(duì)象的形狀
部分.
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.
這篇關(guān)于為什么我不能對(duì)普通變量進(jìn)行多態(tài)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!