C++ 重载 重写与重定义

重载:函数名相同 参数列表不一致 重载只是在类的内部存在

重写:也叫做覆盖 子类重新定义父类中有相同名称和参数的虚函数。

函数特征相同,但具体实现不同,主要是继承关系中出现的

(1)函数必须是虚函数virtual 不能是static函数

(2)重写函数必须有相同类型,名称和参数列表

(3)重写函数的访问修饰符可以不同


重定义也叫隐藏,子类重新定义父类中有相同名称的非虚函数

例子:

#include<iostream>
using namespace std;


class Base {
private:
	virtual void display() {                    //虚函数 
		cout << "Base Dispaly()" << endl;
	}

	void say() {                                //非虚函数   
		cout << "say()" << endl;  
	}

public:
	void excu() {
		display();
		say();
	}

	void f1(int n) {
		cout << "f1 int use" << endl;
	}
	
	void f1(char n) {
		cout << "f1 char use" << endl;
	}
};

class DeriveA :public Base {

public:
	void display() {
		cout << "DeriveA Display" << endl;
	}

	void f1(int a, int b) {
		cout << "f1 double int used" << endl;
	}

	void say() {
		cout << "DriveA say()" << endl;
	}

};


class DeriveB :public Base {

public:
	void f1(int a) {
		cout << "Derive B d1 Use" << endl;
	}
};


int main() {

	DeriveA A;
	A.excu();   //执行父类中的函数  此时可以看到 父类中的virtual函数被重写
	//而say函数使用了父类中的函数

	A.say();   //使用子类中重定义的say函数

	
	Base *B = &A;     //父类使用子类进行实例化
	B->excu();        //使用父类中的函数 virtual除外


	system("PAUSE");
	return 0;
}


执行结果:



由此可知

重载的特征:

(1)相同的范围(在同一个类中)

(2)函数名字相同

(3)参数不同

(4)virtual关键字可有可无


重写是指派生类函数覆盖基类函数:

(1)不同的范围 分别位于基类和派生类中

(2)函数名相同

(3)参数相同

(4)必须带有virtual关键字


重定义是指派生类函数屏蔽了父类中的同名函数(存在两个同名函数 可分别调用 但父类中的被隐藏)

(1)派生类函数和基类函数同名 如果参数不同 此时不管有无virtual 基类函数被隐藏

(2)如果派生类的函数与基类函数同名 如果参数相同 但无virtual 则基类函数隐藏


区分重载和重写

class A{
public:
      virtual int fun(){}
};

class B:public A{
       int fun(int a){}  //这是重载而不是重写:
}

int mian()
{

}


class B:public A{
       int fun() // 从A继承来的 fun, 编译器会自己偷偷帮你加上
       int fun(int a){} // 新的fun, 和前面的只是名字一样的重载函数, 不是虚函数
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值