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;
}
4

1 回答 1

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()
于 2012-06-27T13:02:44.597 回答