【问题标题】:Call extended class function调用扩展类函数
【发布时间】:2013-05-15 09:56:42
【问题描述】:

所以我有一个名为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 没有 setSomething 方法,因此您不能在 Person 或指向 Person 的指针上调用它。
  • 我添加了 Patient 扩展了 Person 所以我认为它可以工作......
  • 既然数组的所有元素都是新的 Patient 类,我可以调用 Patient 类的函数吗?
  • @juanchopanza 你是对的,对不起!
  • @fxuser:数组的元素是患者,但就编译器而言,保证它们是人员,仅此而已:Person *ppl[5]

标签: c++ class oop function derived


【解决方案1】:

您有一个Person* 数组。您只能在该数组的元素上调用 Person 的公共方法,即使它们指向 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
}

【讨论】:

    【解决方案2】:

    编译器不知道指针指向Patient 对象,所以你必须明确告诉编译器它是:

    static_cast<Patient*>(ppl[0])->setSomething(...);
    

    要么这样,要么在基类中将setSomething 设为virtual 函数。

    一个小提示:仅当您确定指针是指向Patient 对象的指针时,使用static_cast 才有效。如果没有变化,则必须改用dynamic_cast,并检查结果是否不是nullptr

    【讨论】:

      猜你喜欢
      • 2012-02-11
      • 1970-01-01
      • 2014-05-29
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多