一个关于继承的问题!
#include <iostream>
#include <string>
using namespace std ;
class Person
{
public:
string name ;
int age ;
Person()
{
name = "Ben" ;
age = 18 ;
}
//virtual
void GetInfo()
{
cout<<"name: "<<name<<" "<<"age: "<<age<<endl ;
}
void display()
{
this->GetInfo() ;
}
};
class Student : public Person
{
public:
string school;
Student():Person()
{
school = "No.1" ;
}
//virtual
void GetInfo()
{
cout<<"name: "<<name<<" "<<"age: "<<age<<" "<<"school: "<<school<<endl ;
}
};
int main()
{
Person P ;
P.display() ;
P.GetInfo();
Student S ;
S.display() ;
S.GetInfo() ;
cout<<endl ;
Person *p = new Student ;
p->display() ;
p->GetInfo() ;
Student *s = new Student ;
s->display() ;
s->GetInfo() ;
delete p;
delete s;
system("pause") ;
return 0 ;
}
在未使用virtual的情况下为什么P.display() ;和S.display() ; 的结果都是一样~而且都是调用父类的GetInfo方法?这是什么原因?C++的语言机制是怎么对待这种
情况?