2012-06-27 47 views
2

我想在C++中調用父類(父類)的繼承函數。
這怎麼可能?如何從父類調用函數?

class Patient{ 
protected: 
    char* name; 
public: 
    void print() const; 
} 
class sickPatient: Patient{ 
    char* diagnose; 
    void print() const; 
} 

void Patient:print() const 
{ 
    cout << name; 
} 

void sickPatient::print() const 
{ 
    inherited ??? // problem 
    cout << diagnose; 
} 
+0

其他什麼類來自患者?如果你的答案不同於「only healthyPatient」,那麼你的設計是錯誤的。 –

回答

10
void sickPatient::print() const 
{ 
    Patient::print(); 
    cout << diagnose; 
} 

而且還如果你想多態行爲,你不得不在基類打印virtual

class Patient 
{ 
    char* name; 
    virtual void print() const; 
} 

在這種情況下,你可以這樣寫:

Patient *p = new sickPatient(); 
p->print(); // sickPatient::print() will be called now. 
// In your case (without virtual) it would be Patient::print()