C++ 中的运算符重载

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

// Box 类
class Box
{
// 属性,用 private 修饰,只有本类才可以访问
private: 
	double length;
	double width;
	double height;
// 方法
public:
	// 设置长、宽、高
	void setLength(double len)
	{
		length = len;
	}
	void setWidth(double wid)
	{
		width = wid;
	}
	void setHeight(double hei)
	{
		height = hei;
	}
	// 求体积
	double getVolumn()
	{
		return length * width * height;
	}
	// 重载 "+" 运算符,用于把两个 Box 对象相加,operator是关键字,不能变,后面的+号是运算符
	Box operator+(const Box &b)
	{
		/*
		this表示当前对象(这里是指针),比如:box3 = box1 + box2,这时候this就表示box1,
		而形参中的Box &b表示Box对象的引用,用const修饰表示程序执行的时候不能被改变
		*/
		Box box;
		box.length = this->length + b.length;	// this.length表示box1.length
		box.width = this->width + b.width;		// b.width表示box2.width
		box.height = this->height + b.height;	// box.height表示新定义的Box对象
		return box;
	}
};

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

	// box1
	box1.setLength(1.0);
	box1.setWidth(2.0);
	box1.setHeight(3.0);
	volumn = box1.getVolumn();
	cout << "box1的体积:" << volumn << endl;

	// box2
	box2.setLength(4.0);
	box2.setWidth(5.0);
	box2.setHeight(6.0);
	volumn = box2.getVolumn();
	cout << "box2的体积:" << volumn << endl;

	// box3 = box1 + box2;	
	box3 = box1 + box2;	// 相当于:box3.length = box1.length + box2.length,width和height也一样各自相加
	volumn = box3.getVolumn();
	cout << "box3的体积(box1+box2):" << volumn << endl;

	system("pause");	// 让窗口停住
	return 0;
} 

 运行:

 

 

posted @ 2018-03-01 17:20  半生戎马,共话桑麻、  阅读(149)  评论(0)    收藏  举报
levels of contents