运算符重载

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

#include 
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 
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;
}




你可能感兴趣的:(C++基础)