C++ 函数重载和运算符重载

一. 函数重载

定义:声明几个功能类似的同名函数,但这些函数形参的个数、类型、顺序(至少其一)必须不同,返回类型必须相同。

例子:

#include<iostream>
using namespace std;

class printData
{
public:
	void print(int i) {
		cout << "整数为:" << i << endl;
	}
	void print(double f) {
		cout << "浮点数为:" << f << endl;
	}
	void print(char c[]) {
		cout << "字符串为:" << c << endl;
	}
};

int main(void)
{
	printData pd;

	pd.print(3);//输出整数
	
	pd.print(30.444);//输出浮点数
	
	char c[] = "Hello C++";
	pd.print(c);//输出字符串

	return 0;
}

结果:

二.运算符重载

重载运算符后可以使用自定义类型的运算符

重载的运算符实质上是一个函数,这个函数的函数名的组成为:operator运算符

整体的函数为:返回值类型  函数名(参数列表)

运算符函数构成:返回值类型  operator运算符 (参数列表)

eg:Complex  operator+(const  Complex&);

此函数可为成员函数  或  非成员函数

例子:

#include<iostream>
using namespace std;

class Box
{
public:
	double getVolume() {
		return length * breadth * height;//计算体积
	}
	//设置长宽高
	void setLength(double len) {
		length = len;
	}
	void setBreadth(double bre) {
		breadth = bre;
	}
	void setHeight(double hei) {
		height = hei;
	}
	//重载运算符+,用于把两个对象相加
	Box operator+(const Box& b) {
		Box box;
		box.length = this->length + b.length;
		box.breadth = this->breadth + b.breadth;
		box.height = this->height + b.breadth;
		return box;
	}
private:
	double length;  //长
	double breadth; //宽
	double height;  //高
};

int main()
{
	Box box1, box2, box3;
	double volume = 0.0;

	box1.setLength(1.0);
	box1.setBreadth(2.0);
	box1.setHeight(3.0);

	box2.setLength(2.0);
	box2.setBreadth(2.0);
	box2.setHeight(2.0);

	volume = box1.getVolume();
	cout << "volume of box1:" << volume << endl;

	volume = box2.getVolume();
	cout << "volume of box2:" << volume << endl;

	box3 = box1 + box2;

	volume = box3.getVolume();
	cout << "volume of box3:" << volume << endl;

	return 0;
}

结果:

如有错误,还请指正。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值