一:基类指针与子类指针
#include "pch.h"
#include <iostream>
using namespace std;
class human
{
public:
void eat() { cout << "各种粮食" << endl; };
};
class man :public human
{
public:
void eat() { cout << "面食" << endl; };
};
class woman :public human
{
public:
void eat() { cout << "米饭" << endl; };
};
int main()
{
human *phuman = new human;
man *pman = new man;
woman *pwoman = new woman;
human *phuman1 = new man;
phuman1->eat();
return 0;
}
二:虚函数
#include "pch.h"
#include <iostream>
using namespace std;
class human
{
public:
virtual void eat() { cout << "各种粮食" << endl; };
};
class man :public human
{
public:
void eat() { cout << "面食" << endl; };
};
class woman :public human
{
public:
void eat() { cout << "米饭" << endl; };
};
int main()
{
human *phuman = new man;
phuman->eat();
human *phuman1 = new man;
phuman1->human::eat();
return 0;
}
三:override与final关键字
c++11引入的override与final关键字在虚函数中的应用。
说明:override只能在子类中使用,而final只能在父类中使用,并且是只能用在虚函数上(或者是用在基类上,用来阻止派生类的继承)。
final与override相对,在父类的虚函数加上它以后,就是说,不要希望在子类中去覆盖父类的eat函数,用了final以后,再用override就不可以了。或者说是用了final以后,子类中就不能在写eat函数了。
#include "pch.h"
#include <iostream>
using namespace std;
class human
{
public:
virtual void eat() { cout << "各种粮食" << endl; };
};
class man :public human
{
public:
void eat() { cout << "面食" << endl; };
};
class woman :public human
{
public:
void eat(int a) override{ cout << "米饭" << endl; };
};
int main()
{
human *phuman = new man;
phuman->eat();
human *phuman1 = new man;
phuman1->human::eat();
return 0;
}
附:有那些函数不能声明为虚函数:
https://www.cnblogs.com/dingou/p/11627596.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)