C++中触发动态绑定条件:1、虚函数成员 2、通过基类类型的引用或指针进行函数调用
例子说明:
#include<iostream>
#include<string>
using namespace std;
class Base
{
public:
string name;
int age;
Base(string _name,int _age):name(_name),age(_age){}
void talk()
{
cout<<name<<" is talking"<<endl;
}
virtual void eat()
{
cout<<name<<" is eating"<<endl;
}
};
class Son:public Base
{
public:
int height;
Son(string _name,int _age,int _h):Base(_name,_age)
{
height=_h;
}
void talk()
{
cout<<name<<",whose height is "<<height<<",is talking loudly!"<<endl;
}
void eat()
{
cout<<name<<" is eating fast!"<<endl;
}
};
int main()
{
Base person("lily",41);
Base* p=&person;
cout<<"基类类型指针指向基类对象:"<<endl;
p->talk();
p->eat();
cout<<"派生类类型指针指向派生类对象:"<<endl;
Son ason("mike",21,180);
Son* q = &ason;
q->talk();
q->eat();
cout<<"基类类型指针指向派生类对象:"<<endl;
p = &ason;
p->talk();
p->eat();
return 0;
}
virtual函数声明调用基类,无virtual函数声明调用的区别
基类类型指针调用派生类: p->talk() 与 p->eat()