在派生类中调用重写方法

时间:2014-10-13 08:03:16

标签: c++ inheritance derived-class

假设我们有3个班级:人,学生和工人。学生和工人都来自人。我想制作一组人员,其中包括随机定位学生和工人实例。在Student和Worker中有一个名为show()的方法重载,我想调用该函数而不是Person show()方法。我知道如何通过像(Student *)或(Worker *)一样转换Person对象,如何在数组中使用该方法?下面是一些示例代码;

类人物:

Person::Person() {    
    this->name = new std::string("Gabi");
    this->age = 12;
}

void Person::show() {   
    std::cout << "Hi my name is " << *(this->name) << std::endl;
    std::cout << "and I am " << this->age << " years old" << std::endl;
}

班级学生:

Student::Student() { 
    this->school = new std::string("ghica");
}

void Student::show() {

    Person::show();
    std::cout << "My school is " << *(this->school) << std::endl;
}

班级工人:

Worker::Worker() {
    this->workplace = new std::string("google");
}

void Worker::show() { 
    Person::show();
    std::cout << "My workplace is " << *(this->workplace) << std::endl;
}

如果我以这种方式调用show()方法:

Person * myperson = new Student("Andrei", 29, "ghica");
myperson->show();

学校信息不会出现,但如果我这样做:

Person * myperson = new Student("Andrei", 29, "ghica");
((Student*)myperson)->show();

确实如此。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

show类中的Person方法声明为 virtual

class Person
{
    ....
    virtual void show();
    ....
};

此外,即使与问题无关,在每个成员变量使用前放置this->通常也是无用的;另外,我看到你声明nameschool作为指向字符串的指针:在大多数情况下,这是不必要和错误的,因为你放弃了value semantic

答案 1 :(得分:2)

重写方法不足以通过指向基类的指针/引用来调用它。你需要把它变成虚拟的:

class Person {
public:
  virtual void show() { // Virtual function
      std::cout << "person show";
  }
};

class Worker : public Person {
public:    
  void show() {
      std::cout << "Worker show";
  }
};

int main() {

    Person obj;
    Worker obj2;

    Person* array[2];
    array[0] = &obj;
    array[1] = &obj2;


    array[0]->show(); // Person
    array[1]->show(); // Worker

   return 0;
}

Example