重载、重写(覆盖)、隐藏(重定义)

1 要求和区分

1)重载要求:函数名相同,参数不同(个数、类型)、常函数也可以作为重载判断。注意返回值不是重载的判断标准。

2)重写(即覆盖)要求:要求基类函数为虚函数,且基类函数和派生类函数名、参数等相同。

3)隐藏(即重定义)要求:子类重新定义父类中有相同名称的非虚函数(参数列表可以不同)。

4)重写和隐藏都是发生在基类和子类中。

 

2 重载代码演示

#include "stdafx.h"
#include <iostream>


/*-------------------------
//   重载
-------------------------*/ 
class Overload{
public:
	Overload(){};
	~Overload(){};
	void displayNumType(int) { std::cout << " number is int " << std::endl; }
	void displayNumType(short) { std::cout << " number is short " << std::endl; }
	void displayNumType(double) { std::cout << " number is double " << std::endl; }
	void displayNumType(int, double) { std::cout << " number1 is int, number2 is double " << std::endl; }
	void displayNumType(double, int) { std::cout << " number1 is double, number2 is int " << std::endl; }
	void displayNumType(int) const { std::cout << " number is int and function is const " << std::endl; }
};


int main(){

	Overload r;
	int num1 = 5;
	short num2 = 5;
	double num3 = 5;
	r.displayNumType(num1);
	r.displayNumType(num2);
	r.displayNumType(num3);
	r.displayNumType(num1, num3);
	r.displayNumType(num3, num1);
	
	const Overload r1;
	r1.displayNumType(num1);

	return 0;
}


结果显示:
 number is int
 number is short
 number is double
 number1 is int, number2 is double
 number1 is double, number2 is int
 number is int and function is const
请按任意键继续. . .

 

3 覆盖代码演示

#include "stdafx.h"
#include <iostream>


/*-------------------------
//   覆盖
-------------------------*/
class A{
public:
	virtual void display() { std::cout << "This is Base" << std::endl; }
};


class B : public A{
public:
	void display() { std::cout << "This is derived" << std::endl; }
	void display1() { std::cout << "This is derived" << std::endl; }
};


int main(){
	A *a = new B;
	B b;
	a->display();
	//a->display1();
	b.display();
	b.display1();
}


结果显示:
This is derived
This is derived
This is derived
请按任意键继续. . .

至于为什么a->display1() 会出现错误?

因为display1()不是A的成员。

从上面的代码可以看出,覆盖(重写)主要是虚函数多态时使用,而重载也是多态的一种,两者不一样!

 

4 隐藏代码演示

#include "stdafx.h"
#include <iostream>


/*-------------------------
//   隐藏
-------------------------*/
class A{
public:
	void display() { std::cout << "This is Base" << std::endl; }
};


class B : public A{
public:
	void display() { std::cout << "This is derived" << std::endl; }
};


int main(){
	A a;
	B b;
	a.display();
	b.display();
	return 0;
}


结果显示:
This is Base
This is derived
请按任意键继续. . .


备注:如果将B中的display注释掉,结果显示为:
This is Base
This is derived

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值