#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 ++的情况下,基类指针正在调用自己的draw方法。不知道这个问题背后的原因。
C ++的输出是
drawing shape
drawing circle
************************
drawing shape
java的输出是
Drawing the shape
Drawing Circle
************************
Drawing Circle
答案 0 :(得分:1)
Java方法是隐式虚拟的,因此您希望C ++代码使用&#39;虚拟&#39;关键字,以便重现与Java示例相同的行为:
class Shape
{
public:
virtual void draw();
};
class Circle : public Shape
{
public:
virtual void draw() override; //C++11 'override'
};
或者,如果您希望Java代码具有与C ++示例相同的行为,则需要将Java方法声明为&#39; final&#39;:
public class Shape
{
public final void draw()
{
...
}
}
public class Circle extends Shape
{
public final void draw()
{
...
}
}