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

在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。不能仅通过返回类型的不同来重载函数。

下面的实例中,同名函数 print() 被用于输出不同的数据类型:

#include <iostream>

using namespace std;

class Printf
{
	public :
	void print( int x )
	{
		cout << "int = " << x << endl;
	}
	void print( double x )
	{
		cout << "float = " << x << endl;
	}
	void print( char x[] )
	{
		cout << "char [] = " << x << endl;
	}
};

int main()
{
	Printf Pf;
	Pf.print(5);
	Pf.print(8.8);
	Pf.print("abc");

	return 0;
}

 

我们可以重定义或重载大部分 C++ 内置的运算符。这样就能使用自定义类型的运算符。

下面的实例中,+运算符被用于Box对象的加法:

#include <iostream>

using namespace std;

class Box
{
	public:
	
	int getVolume()
	{
		return (width * height *length);
	}
	
	void setWidth( float x )
	{
		width = x;
	}
	
	void setHeight( float x )
	{
		height = x;
	}
	
	void setLehgth( float x )
	{
		length = x;
	}
	
	Box operator+( const Box& x )
	{
		Box Res;
		Res.width = x.width + this->width;
		Res.height = x.height + this->height;
		Res.length = x.length + this->length;
		return Res;
	}
	
	protected:
	
	float width;
	float height;
	float length;
};

int main()
{
	Box box1,box2,box3;
	float Box1Volume , Box2Volume , Box3Volume;
	
	box1.setWidth(1);
	box1.setHeight(2);
	box1.setLehgth(3);
	
	box2.setWidth(4);
	box2.setHeight(5);
	box2.setLehgth(6);
	
	Box1Volume = box1.getVolume();
	Box2Volume = box2.getVolume();
	cout << Box1Volume << endl;
	cout << Box2Volume << endl;
	
	box3 = box1 +box2;
	Box3Volume = box3.getVolume();
	cout << Box3Volume << endl;
	
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值