gpt4 book ai didi

c++ - 如何调用父类的函数?

转载 作者:太空狗 更新时间:2023-10-29 23:41:25 25 4
gpt4 key购买 nike

我想在C++中调用父类(super class)(父类)的继承函数。
这怎么可能?

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

最佳答案

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

而且,如果你想要多态行为,你必须在基类中制作 print 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()

关于c++ - 如何调用父类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11226825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com