C++面向对象三大特性:封装 继承 多态,回避虚函数的机制
#include <iostream>
using namespace std;
class Animal
{
public :
string kind;
string color;
void showMsg()
{
cout << kind << color << endl;
}
void eat()
{
cout << "吃东西" << endl;
}
};
// class 声明的类默认的继承方式是private
class Dog : public Animal
{
public:
void eat()
{
// 重写 对于基类当中的方法进行重新编写 必须保证函数名相同
cout << "火腿" << endl;
}
};
class Cat : public Animal
{
};
int main()
{
Dog d1;
d1.kind = "哈士奇";
d1.color = "黑色";
d1.showMsg();
d1.eat();
// C++默认的是静态绑定 当程序编译时期就确定了结果
// 多态 实际就是动态绑定 继承+函数重写+虚函数 + 父类的引用或指针指向子类的对象
Animal &a1 = d1;
a1.showMsg();
a1.eat();
Animal *pa = &d1;
pa->showMsg();
pa->eat();
return 1;
}
输出结果为:
哈士奇黑色
火腿
哈士奇黑色
吃东西 /* 可见子类中重写的eat函数没有生效,没有起到多态的作用
*/
哈士奇黑色
吃东西
修改代码增加关键字 virual
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
class Animal
{
public :
string kind;
string color;
void showMsg()
{
cout << kind << color << endl;
}
// 对于重写的函数 完成一个virtual定义 此时该函数变成虚函数
virtual void eat()
{
cout << "吃东西" << endl;
}
};
// class 声明的类默认的继承方式是private
class Dog : public Animal
{
public:
virtual void eat()
{
// 重写 对于基类当中的方法进行重新编写 必须保证函数名相同
cout << "火腿" << endl;
}
};
class Cat : public Animal
{
};
int main()
{
Dog d1;
d1.kind = "哈士奇";
d1.color = "黑色";
d1.showMsg();
d1.eat();
// C++默认的是静态绑定 当程序编译时期就确定了结果
// 多态 实际就是动态绑定 继承+函数重写+虚函数 + 父类的引用或指针指向子类的对象
Animal &a1 = d1;
a1.showMsg();
a1.eat();
Animal *pa = &d1;
pa->showMsg();
pa->eat();
return 1;
}
执行结果:
哈士奇黑色
火腿
哈士奇黑色
火腿
哈士奇黑色
火腿
类:封装 、继承
vurtual:虚函数多态的实现
一旦某个函数被声明为虚函数后,则在所有派生类中都是虚函数
在某些情况下,我们希望对虚函数的调用不要进行动态绑定,而是强迫执行虚函数的某个特定版本。则通过作用域可以实现这一目的。
//增加作用域就OK了
pa->Animal::showMsg();
pa->Animal::eat();
回避虚函数的机制:
基类的版本通常完成继承层次中所有类型都要做的共同任务,而派生类中定义的版本需要执行一些与派生类本身密切相关的行为。
标题
C++面向对象三大特性:封装 继承 多态,回避虚函数的机制