运算符重载

复数类的实现以及加号和减号的重载

#include <iostream>
using namespace std;

//复数类定义
class Complex
{
private:
	double real;
	double imag;
public:
	Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {}
	//运算符+重载成员函数
	Complex operator+ (const Complex& op) const;
	//运算符-重载成员函数
	Complex operator- (const Complex& op) const;
	void display() const {  printf("( %.2f, %.2f)", real, imag);}
};

Complex Complex::operator+(const Complex& op) const
{
	//创建一个临时无名对象作为返回值
	return Complex(real + op.real, imag + op.imag);
}
Complex Complex::operator-(const Complex& op) const
{
	return Complex(real - op.real, imag - op.imag);
}

int main()
{
	Complex c1(5, 4), c2(2, 10);
	Complex c3 = c1 + c2;
	c3.display();
	cout << endl;
	c3 = c1 - c2;
	c3.display();
	cout << endl;
    return 0;
}

单目运算符++的重载

#include <iostream>
using namespace std;

class Clock
{
private:
	int hour, minute, second;
public:
	Clock(int h = 0, int m = 0, int s = 0);
	//前置单目运算符重载
	Clock& operator++();
	//后置单目运算符重载
	Clock operator++(int);
	void display() const { printf(" %d : %d : %d", hour, minute, second); }
};

Clock::Clock(int h, int m, int s)
{
	if (0 <= h&&h <= 23 && 0 <= m && m <= 59 && 0 <= s && s <= 59)
	{
		hour = h;
		minute = m;
		second = s;
	}
	else
		printf("Time's values error.");
}

Clock Clock::operator++(int)
{
	Clock old = *this;
	++(*this);
	return old;
}

Clock& Clock::operator++()
{
	//如果Clock& Clock::operator++() const,则此时通过常量对象访问“sec”,因此无法对其进行修改
	++second;
	if (second > 59)
	{
		second -= 60;
		++minute;
		if (minute > 59)
		{
			minute -= 60;
			hour = (hour + 1) % 24;
		}
	}
	return *this;
}

int main()
{
	Clock MyClock(23, 59, 59);
	MyClock.display(); cout << endl;
	(MyClock++).display(); cout << endl;
	MyClock.display(); cout << endl;
	(++MyClock).display(); cout << endl;
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值