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

C++ 中的函数重载

class PrintData
{
	public:
		void print(int v)
		{
			cout << "cout v=" << v << endl;
		}
		void print(double b)
		{
			cout << "cout b=" << b << endl;
		}
		void print(char c[])
		{
			cout << "cout c" << c << endl;
		}
	private:

};


int main(void)
{
	PrintData pd;
	pd.print(8);
	pd.print(88.888);
	char c[] = "打印字符串";
	pd.print(c);
	return 0;
}

//打印结果
cout v=8
cout b=88.888
cout c打印字符串

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

int main(void)
{
	Box Box1;                // 声明 Box1,类型为 Box
	Box Box2;                // 声明 Box2,类型为 Box
	Box Box3;                // 声明 Box3,类型为 Box
	double volume = 0.0;     // 把体积存储在该变量中

	Box1.setLength(1.0);
	Box1.setBreadth(1.0);
	Box1.setHeight(1.0);

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

	volume = Box1.getVolume();
	cout << "box1体积=" << volume << endl;

	volume = Box2.getVolume();
	cout << "box2体积=" << volume << endl;

	Box3 = Box1 + Box2;
	//1+2 * 1+2 * 1+2
	volume = Box3.getVolume();
	cout << "box3体积=" << volume << endl;
	return 0;
}
//打印结果
box1体积=1
box2体积=8
box3体积=27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ob杨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值