重写(override),重载(overload),重定义(redefine)的区别 参见:http://www.cnblogs.com/BeyondTechnology/archive/2010/09/20/1831441.html
重写又称为覆盖,是指父类的虚函数在子类中被重写(覆盖),返回值和参数列表相同。
一般来说,如果父类的某个函数用virtual修饰,即使派生类中的同名函数没有用virtual修饰,只有满足下列条件,派生类的该函数也是虚函数:
函数名字相同,参数列表相同(个数和类型),返回值相同或者满足类型兼容规则。
重定义是指对父类的函数(不是virtual修饰的)重新定义。
重载是指具有相同的函数名,不同的参数列表(必须不同)的函数。(与返回值无关)
- #include <iostream>
- using namespace std;
-
- class Base
- {
- public:
- //重载
- //函数名相同,参数列表(参数个数或者类型)不同,与返回值无关
- void fun1(int a){cout<<a<<endl;}
- void fun1(double a){cout<<a<<" double "<<endl;}
-
- void fun2(int a,int b){cout<<"fun2() of Base!"<<endl;}
-
- virtual void fun3(){cout<<"virtual void fun3() of Base"<<endl;}
- };
-
- class Derived:public Base
- {
- public:
- void fun2(int a,int b){cout<<"fun2() of Derived!"<<endl;} //重定义父类的fun2()函数
-
- virtual void fun3(){cout<<"void fun3() of Derived!"<<endl;} //覆盖(重写)父类的fun3()函数
- };
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- Base* b1=new Base;
-
- b1->fun1(1);
- b1->fun1(1.0);
- b1->fun2(1,2);
- b1->fun3();
-
- Base* b2=new Derived; //父类的指针指向子类的对象
-
- b2->fun1(1);
- b2->fun1(1.0);
- b2->fun2(1,2); //实际调用的是父类的,因为没有使用virtual
- b2->fun3();
-
- return 0;
- }
|