2015-11-14 112 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