我不明白为什么在我没有使用virtual关键字的情况下,将派生类强制转换为基类的指针会调用派生类方法。这是正常行为吗?指针不是将Person对象保存在内存中,因此将其传递给Student应该不会对其内容产生任何影响?
class Person {
public:
Person()
{
cout << "Creating Person Class" << endl;
}
void about_me()
{
cout << "I am a person" << endl;
}
};
class Student : protected Person {
public:
Student()
{
cout << "Creating Student Class" << endl;
}
void about_me()
{
cout << " I am a student " << endl;
}
};
int main()
{
Person* pperson = new Person();
Student* pstudent = new Student();
pperson->about_me();
pstudent->about_me();
pperson-> about_me();
((Student*)pperson)-> about_me(); // this is the line where I do the cast
return 0;
}
代码的输出如下所示
Creating Person Class
Creating Person Class
Creating Student Class
I am a person
I am a student
I am a person
I am a student
https://stackoverflow.com/questions/52175292
复制相似问题