C++的使用小教程5——类的重载

学习好幸苦。
在这里插入图片描述

1、类的重载是什么

C++的重载分为两类,一个是函数的重载,一个是运算符的重载,重载的意思就是允许在一个作用域内对函数或者运算符指定多个定义,以实现不同的功能。
其中函数的重载是,在同一个作用域内,可以声明与定义几个名字相同的函数,但是其形式参数不同(不同包括形式参数类型、多少、顺序等等),但是必须注意的是不能仅通过返回类型的不同来重载函数。
其中运算符的重载是,这里用一个例子来说明,**假设我们定义了一个int a = 5,int b = 10;此时调用int c = a + b;得到c = 15。**但是对于我们自己定义的class而言,比如class Box,那么box3 = box1 + box2;是什么意思呢?这就是运算符的重载需要定义的。

2、函数的重载

在同一个作用域内,可以声明与定义几个名字相同的函数,但是其形式参数不同(不同包括形式参数类型、多少、顺序等等),但是必须注意的是不能仅通过返回类型的不同来重载函数。
在接下来的举例中,我将通过打印字符串实现函数的重载。

#include <iostream>
#include <string>
using namespace std;

class printExample
{
public:
	void print(int i) {
		cout << "此时输出为整型:" << i << endl;
	}

	void print(double  d) {
		cout << "此时输出为浮点型:" << d << endl;
	}

	void print(string s) {
		cout << "此时输出为字符串: " << s << endl;
	}
};

int main(void)
{
	printExample test;

	// 此时输出为整型
	test.print(5);
	// 此时输出为浮点型
	test.print(500.263);
	// 此时输出为字符串
	test.print("OK");

	
	system("pause");
	return 0;
}

输出结果为:

此时输出为整型:5
此时输出为浮点型:500.263
此时输出为字符串: OK
请按任意键继续. . .

3、运算符的重载

我们可以重载C++中大部分的运算符,其重载的格式为:

Box operator+(const Box&);

如上的声明重载的是加法运算符,其作用是把两个 Box 对象相加,返回最终的 Box 对象。在应用时,调用如下函数。

box3 = box2 + box1;

当然,返回对象和重载的运算符都可以修改,只要修改重载格式中的"Box"和"+"即可。
在接下来的例子中,我将通过重载运算符实现两个box的相加,相加的内容是两个box的length和width。

#include <iostream>
#include <cstring>
using namespace std;

/*Box基类*/
class Box 
{
protected:
	int width;
	int length;
public:
	void setWidth(int widthIn);
	void setLength(int lengthIn);
	int getWidth();
	int getLength();
	// 声明运算符重载函数
	Box operator+(const Box& b);
};

void Box::setWidth(int widthIn){
	width = widthIn;
}

void Box::setLength(int lengthIn) {
	length = lengthIn;
}

int Box::getWidth() {
	return width;
}

int Box::getLength() {
	return length;
}

// 定义运算符重载函数
Box Box::operator+(const Box& b)
{
	Box box;
	box.width = this->width + b.width;
	box.length = this->length + b.length;
	return box;
}

int main()
{
	Box smallbox;
	Box box;
	Box bigbox;

	smallbox.setLength(5);
	smallbox.setWidth(5);
	box.setLength(10);
	box.setWidth(10);

	bigbox = smallbox + box;

	cout << "The length of the small box is " << smallbox.getLength() << endl;
	cout << "The length of the box is " << box.getLength() << endl;
	cout << "The length of the big box is " << bigbox.getLength() << endl;
	system("pause");
}

输出结果为:

The length of the small box is 5
The length of the box is 10
The length of the big box is 15
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bubbliiiing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值