C++程序设计学习笔记之多态虚函数
live long and prosper
多态是C++类的中重要性质,虚函数是体现多态的重要标志,在父类中,父类成员函数中添加关键字virtual可让成员函数具有多态性。
在下面的例子中,创建了:
Animal类(父类)
{
Cat类; (继承而来)
Dog类; (继承而来)
}
虚函数早绑定
虚函数早绑定,不适用virtual关键字,尝试调用子类成员函数.
#include<iostream>
using namespace std;
class Animal//父类
{
public:
//成员函数speak()
void speak() {
cout << "animal is speaking." << endl;
}
};
/*
-----------------------------------------------------------------------------------------------
地址早绑定,此时程序执行结果为animal is ...,因为speak函数的地址在编译的时候已经绑定到animal上了,
为了绑定到cat上,使用关键字virtual(在animal类中)
-----------------------------------------------------------------------------------------------
*/
class Cat:public Animal//子类,从父类继承
{
public:
//继承父类的成员函数speak(),并重写
void speak() {
cout << "cat is speaking." << endl;
}
};
//执行成员函数。
void dospeak(Animal &animal) {
animal.speak();
}
//测试函数,创建一个实例类。
void test() {
Cat cat;
dospeak(cat);
}
int main()
{
cout << "--------" << endl;
test();
return 0;
}
显然,无效。
虚函数晚绑定
#include<iostream>
using namespace std;
class Animal
{
public:
//虚函数
//地址晚绑定
//为了绑定到cat上,使用关键字virtual(在animal类中)
virtual void speak() {
cout << "animal is speaking." << endl;
}
};
class Cat:public Animal
{
public:
void speak() {
cout << "cat is speaking." << endl;
}
};
void dospeak(Animal &animal) {
animal.speak();
}
void test() {
Cat cat;
dospeak(cat);
}
int main()
{
cout << "--------" << endl;
test();
return 0;
}
执行结果为:cat is speaking.