虚函数跟普通函数的区别就是当基类指针或引用指向派生类对象时,通过指针或引用调用成员函数,对于非虚函数,调用的是静态类型(指针/引用类型)的版本,对于虚函数,在运行时动态绑定,调用的是实际类型的版本。例子看输出的前两行。
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
virtual void test()
{
cout<<"A:test()"<<endl;
};
void foo()
{
cout<<"A:foo()"<<endl;
};
};
class B : public A
{
public:
void test(){
cout<<"B:test()"<<endl;
};
void foo(){
cout<<"B:foo()"<<endl;
};
};
int _tmain(int argc, _TCHAR* argv[])
{
A* a = new B;
a->test();//虚函数,动态绑定,调用动态类型(实际对象类型)B版本
a->foo();//非虚函数,调用静态类型(指针类型)A的版本
B* b = new B;
b->test();//虚函数,动态绑定,调用动态类型B版本
b->foo();//非虚函数,调用静态类型(指针类型)A的版本
b->A::foo();//这两个指定是调用A类版本
b->A::test();
return 0;
}