[英]Calling an overridden method in a derived class
Let's suppose we have 3 classes: Person, Student and Worker. 假设我们有3个班级:人,学生和工人。 Student and Worker both are derived from Person.
学生和工人均来自“人”。 I want to make an array of persons, which consists of randomly position Student and Worker instances.
我想组成一个人数组,其中包括随机放置的Student和Worker实例。 There is a method called show() overloaded in both Student and Worker and I want to call that function instead of the Person show() method.
在Student和Worker中都有一个重载的show()方法,我想调用该函数而不是Person的show()方法。 I know how to do by casting the Person object like (Student*) or (Worker*) how could I use that method in array?
我知道如何通过将Person对象转换为(Student *)或(Worker *)来进行操作,如何在数组中使用该方法? Below is some sample code;
下面是一些示例代码;
class 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;
}
class Student: 班级学生:
Student::Student() {
this->school = new std::string("ghica");
}
void Student::show() {
Person::show();
std::cout << "My school is " << *(this->school) << std::endl;
}
class Worker: 类工人:
Worker::Worker() {
this->workplace = new std::string("google");
}
void Worker::show() {
Person::show();
std::cout << "My workplace is " << *(this->workplace) << std::endl;
}
If I call the show() method this way: 如果我这样调用show()方法:
Person * myperson = new Student("Andrei", 29, "ghica");
myperson->show();
the school message will not appear, but if I do this: 学校消息不会出现,但是如果我这样做:
Person * myperson = new Student("Andrei", 29, "ghica");
((Student*)myperson)->show();
it does. 是的。 Any ideas?
有任何想法吗?
Declare the show
method in the Person
class as virtual
: 在
Person
类中将show
方法声明为virtual
:
class Person
{
....
virtual void show();
....
};
Also, even if unrelated to the question, it's often useless to place this->
in front of each member variable use; 而且,即使与问题无关,将
this->
放在每个成员变量使用的前面也常常没用; in addition, I see you are declaring name
and school
as pointer to string: in most of cases this is unnecessary and wrong because you are giving up value semantic . 此外,我看到您将
name
和school
声明为指向字符串的指针:在大多数情况下,这是不必要且错误的,因为您放弃了价值语义 。
Overriding a method isn't sufficient to have it called via a pointer/reference to the base class. 重写方法不足以通过指向基类的指针/引用来调用它。 You need to make it virtual:
您需要将其虚拟化:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.