-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++の出力は、javaの出力は、あなたのC++で「仮想」キーワードを使用するコードをしたいと思うよう
Drawing the shape
Drawing Circle
************************
Drawing Circle
C++を実行して以来長いことがありましたが、宣言する必要があると思います'shape :: draw()'を 'virtual'としてオーバーライドできます。 – markspace
PROGRAMMINGに何も問題がないので、この質問を議論の対象外とすることにしました。 –
@ JulianF.Weinert:C++コードは最初に「Shape」クラスを、Javaコードは「Circle」クラスを最初に持っています。 –