如何从父类调用函数?

时间:2012-06-27 13:01:50

标签: c++ oop function

我想在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;
}

1 个答案:

答案 0 :(得分: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()