2016-10-01 68 views
-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 
+0

這是一個很長的時間,因爲我做了任何C++,但我認爲你需要聲明'shape :: draw()'爲'virtual'以允許覆蓋。 – markspace

+0

我投票結束這個問題作爲題外話題,因爲沒有任何編程問題。 –

+0

@ JulianF.Weinert:您最好仔細閱讀示例 - C++代碼首先具有「Shape」類,而Java代碼首先具有「Circle」類。 –

回答

1

Java方法隱含虛擬的,所以你會希望你的C++代碼,使用「虛擬」關鍵字爲了重現與您的Java示例相同的行爲:

class Shape 
{ 
public: 
    virtual void draw(); 
}; 
class Circle : public Shape 
{ 
public: 
    virtual void draw() override; //C++11 'override' 
}; 

或者,如果您希望Java代碼有相同的行爲,你的C++例子中,你需要聲明Java方法作爲「最終」:

public class Shape 
{ 
    public final void draw() 
    { 
     ... 
    } 
} 
public class Circle extends Shape 
{ 
    public final void draw() 
    { 
     ... 
    } 
} 
相關問題