覆盖(重写) vs 重载 vs 重定义

本文详细解释了在面向对象编程中,重写(override)、重定义(redefine)及重载(overload)的概念与区别,并通过示例代码演示了它们在C++中的具体应用。

重写(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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值