所以我有一个类叫做Person
class Person{
private:
public:
Person();
}
和另外 1 个名为 Patient
的类class Patient : public Person{
private:
string text_;
public:
Patient();
void setSomething(string text){ text_ = text; }
}
现在我已经创建了一个包含 5 个喜欢的人的数组
Person *ppl[5];
并在数组的每个键中添加 5 个患者
ppl[0] = new Patient();
ppl[1] = new Patient();
ppl[2] = new Patient();
ppl[3] = new Patient();
ppl[4] = new Patient();
现在我想像这样从Patient类调用setSomething函数
ppl[0]->setSomething("test text");
但我不断收到以下错误:
class Person has no member named setSomething
最佳答案
你有一个数组 Person*
。您只能对该数组的元素调用 Person
的公共(public)方法,即使它们指向 Patient
对象。为了能够调用 Patient
方法,您首先必须将 Person*
转换为 Patient*
。
Person* person = new Patient;
person->setSomething("foo"); // ERROR!
Patient* patient = dynamic_cast<Patient*>(person);
if (patient)
{
patient->setSomething("foo");
} else
{
// Failed to cast. Pointee must not be a Patient
}
关于c++ - 调用扩展类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16561993/