我的问题是:子类继承基类后,若基类中没有虚函数,都有breathe成员函数的定义这时我定义一个指向基类的指针,同时定义一个子类对象,将这个指针指向子类对象,如:animal是基类,fish是子类
animal* A;fish B;A=&B;A->breathe();
按书上说,是发生了强制类型转换,调用了animal中的breathe(),这个我可以理解;
然后若基类中有虚函数breathe,子类中也有同名定义breathe,再执行上面的代码
animal* A;fish B;A=&B;A->breathe();
可以肯定调用的是fish中的breathe()。是不是同样发生了类型强制转换?那么书上说,实际执行breathe时,会自动根据对象的实际类型调用相应的函数。请问这个实际类型是编译器自动保存的吗?是不是不需要我们做别的操作?
请大佬解惑!谢谢!
附完整代码
#include<stdlib.h>
#include<typeinfo.h>
using namespace std;
class animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
void sleep()
{
cout<<"animal sleep"<<endl;
}
virtual void breath()
{
cout<<"animal breath"<<endl;
}
};
class fish:public animal
{
public:
void breath()
{
cout<<"fish breath"<<endl;
}
};
void fn(animal *species)
{
species->breath();
cout<<typeid(species).name()<<endl;
}
void main()
{
fish fh;
animal* fit;
fit=&fh;
fn(fit);
cout<<typeid(fit).name()<<endl;
//cout<<typeid(fh).name()<<endl;
system("pause");
}