c++虚函数讲解
视频:https://www.bilibili.com/video/BV1QV4y1U73z?t=396.0
代码示例(问题引出)
#include <iostream>
using namespace std;
class Animal{
public:
void run(){
cout<<"I don`t know how to run"<<endl;
}
};
class Cat: public Animal{
public:
void run(){
cout<<"I run with 4 legs"<<endl;
}
};
int main()
{
Cat cat;
cat.run();
// 指针
Animal *p = &cat;
p->run();
// 引用
Animal &r = cat;
r.run();
return 0;
}
运行结果
I run with 4 legs
I don`t know how to run
I don`t know how to run
当用父类指针指向子类对象时,用该指针调用父类子类中的同命方法,会执行指针所定义的类中的该方法,而非指向对象中的该方法
如何让指针调用对象而非类中的该方法呢
此时就引入虚函数(实现多态,让指针调用的是指向对象的方法而不是定义指针时前面的那个类中的方法)
代码
#include <iostream>
using namespace std;
class Animal{
public:
virtual void run(){ // 引入虚函数
cout<<"I don`t know how to run"<<endl;
}
};
class Cat: public Animal{
public:
void run()override{ // override是重写标识,可有可无
cout<<"I run with 4 legs"<<endl;
}
};
int main()
{
Cat cat;
cat.run();
// 指针
Animal *p = &cat;
p->run();
// 引用
Animal &r = cat;
r.run();
return 0;
}
输出
I run with 4 legs
I run with 4 legs
I run with 4 legs
问题解决(注意:此处override为一个标识,表示重写父类该函数,就是父类所定义的虚函数,override可写可不写)
多态:通过父类指针或引用调用子类的方法