C++中的动态绑定,是通过Virtual关键字来指定为虚函数,通过基类指针或引用调用。
示例代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//学习Virtual,了解通过Virtual实现动态绑定
class Zone{
public:
Zone(){
cout << "construct a zone" << endl;
}
virtual void func(){
cout << "I'm a zone" << endl;
}
~Zone(){
cout << "destruct Zone" << endl;
}
};
class Country : public Zone{
public:
Country(){
cout << "construct a country" << endl;
}
void func(){
cout << " i'm a country" << endl;
}
~Country(){
cout << "destruct country" << endl;
}
};
class China : public Country{
public:
China(){
cout << "Construct China" << endl;
}
void func(){
cout << "I'm China" << endl;
}
~China(){
cout << "destruct China" << endl;
}
};
int main()
{
FILE* fp = freopen("D:\mylog.txt","w",stdout);
if(NULL == fp) return -1;
Zone* c = new China;
c->func();
delete c;
fclose(fp);
return 0;
}
输出:
construct a zone
construct a country
Construct China
I'm China
destruct Zone
从Log中看到,通过Zone基类指针,指向China子类,调用的是子类的func方法,而不是基类的。
而析构函数只调用了基类的,未调用子类的。
修改方式为在Zone析构函数前加Virtual即可。
打印结果:
construct a zone
construct a country
Construct China
I'm China
destruct China
destruct country
destruct Zone