-4
#include<iostream>
using namespace std;
class shape
{
public: void draw();
};
void shape::draw()
{
cout<<"drawing shape\n";
}
class circle:public shape
{
public: void draw();
};
void circle::draw()
{
cout<<"drawing circle\n";
}
int main()
{
shape* sptr;
circle* cptr;
sptr=new shape();
cptr=new circle();
sptr->draw();
cptr->draw();
cout<<"****************************\n";
sptr=cptr;
sptr->draw();
}
*********************************JAVA CODE*****************************
public class Circle extends Shape{
public void draw() {
System.out.println("Drawing Circle");
}
}
public class Shape {
public void draw()
{
System.out.println("Drawing the shape");
}
}
public class SimulateShape {
public static void main(String[] args){
Shape shape=new Shape();
Circle circle=new Circle();
shape.draw();
circle.draw();
System.out.println("************************");
shape=circle;
shape.draw();
}
}
儘管兩個代碼看起來都一樣,但兩個代碼生成的輸出卻非常不同。在java中,基類引用能夠調用派生類的繪製,但在C++中,情況與基類指針相反的是調用它自己的繪製方法。不知道這個問題背後的原因。相同的繼承代碼在java和C++上的工作方式不同
C++的輸出是
drawing shape
drawing circle
************************
drawing shape
了java的輸出
Drawing the shape
Drawing Circle
************************
Drawing Circle
這是一個很長的時間,因爲我做了任何C++,但我認爲你需要聲明'shape :: draw()'爲'virtual'以允許覆蓋。 – markspace
我投票結束這個問題作爲題外話題,因爲沒有任何編程問題。 –
@ JulianF.Weinert:您最好仔細閱讀示例 - C++代碼首先具有「Shape」類,而Java代碼首先具有「Circle」類。 –