2015-11-14 109 views
0

看看這個例子,有3個類繼承bell。它們覆蓋了bell的不同方法。超類的子類的調用方法

#include <iostream> 
using namespace std; 

class bell { 
public: 
    void noise() { 
     cout << "dung" << endl; 
    } 
    void ring() { 
     noise(); 
     noise(); 
    } 
}; 

class short_bell : public bell { 
public: 
    void ring() { 
     noise(); 
    } 
}; 

class annoying_bell : public bell { 
public: 
    void noise() { 
     cout << "ding" << endl; 
    } 
    void ring() { 
     noise(); 
     noise(); 
     noise(); 
     noise(); 
     noise(); 
    } 
}; 

class slow_bell : public bell { 
public: 
    void noise() { 
     cout << "dooong" << endl; 
    } 
}; 

int main() 
{ 
    cout << "church bell" << endl; 
    bell church_bell; 
    church_bell.ring(); 

    cout << "bicycle bell" << endl; 
    short_bell bicycle_bell; 
    bicycle_bell.ring(); 

    cout << "doorbell" << endl; 
    annoying_bell doorbell; 
    doorbell.ring(); 

    cout << "school bell" << endl; 
    slow_bell school_bell; 
    school_bell.ring(); 

    return 0; 
} 

輸出:

church bell 
dung 
dung 
bicycle bell 
dung 
doorbell 
ding 
ding 
ding 
ding 
ding 
school bell 
dung 
dung 

一切正常,如我所料,但在school_bellslow_bell繼承自bell並覆蓋noise方法。當slow_bellring方法被調用它回落到其父bell但是當bellring方法調用noise它被稱爲的bellnoise方法,而不是我想它調用slow_bellnoise方法。

達到此目的的最佳方法是什麼?

+0

*它們將覆蓋bell' * ** **沒了唐它們的'不同的方法他們只是影射(或繼承)他們。閱讀* polymorphism *的正確介紹,特別是'virtual','override'的使用,還有'= 0'和'final'的使用。 – Walter

回答

2

讓他們virtualoverride方法:

貝爾:

class bell { 
public: 
    virtual void noise() { 
     cout << "dung" << endl; 
    } 
    void ring() { 
     noise(); 
     noise(); 
    } 
}; 

slow_bell:

class slow_bell : public bell { 
public: 
    void noise() override { 
     cout << "dooong" << endl; 
    } 
}; 
+0

我懷疑OP也希望'ring()'是多態的。 – Walter