2012-06-27 53 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()