#include<iostream>
using namespace std;
class Clock
{
public:
Clock(int NewH, int NewM, int NewS);
void ShowTime();
Clock& operator ++(); //前置单目运算符重载
Clock operator ++(int); //后置单目运算符重载
private:
int Hour, Minute, Second;
};
//前置单目运算符重载函数
Clock& Clock::operator ++()
{
Second++;
if (Second >= 60) {
Second -= 60;
Minute++;
if (Minute >= 60) {
Minute -= 60;
Hour = (Hour + 1) % 24;
}
}
return *this;
}
//后置单目运算符重载
Clock Clock::operator ++(int)
{ //注意形参表中的整型参数
Clock old = *this;
++(*this);
return old;
}
Clock::Clock(int NewH, int NewM, int NewS) {
Hour = NewH;
Minute = NewM;
Second = NewS;
}
void Clock::ShowTime() {
cout << Hour << ":" << Minute << ":" << Second << endl;
}
int main()
{
Clock myClock(23, 59, 59);
cout << "First time output:";
myClock.ShowTime();
cout << "Show myClock++:";
(myClock++).ShowTime(); //后置
cout << "Show ++myClock:";
(++myClock).ShowTime(); //前置
return 0;
}
#include<iostream>
using namespace std;
class complex
{
public:
complex(double r = 0.0, double i = 0.0) { real = r; imag = i; }
complex operator + (complex c2); //+重载为成员函数
complex operator - (complex c2); //-重载为成员函数
void display(); //输出复数
private:
double real; //复数实部
double imag; //复数虚部
};
//重载函数实现
complex complex::operator +(complex c2)
{
complex tmp;
tmp.real = c2.real + real ;
tmp.imag = c2.imag + imag ;
return tmp;
}
//重载函数实现
complex complex::operator -(complex c2)
{
complex tmp;
tmp.real = real - c2.real ;
tmp.imag = imag - c2.imag ;
return tmp;
}
void complex::display()
{
cout << "(" << real << "," << imag << ")" << endl;
}
int main()
{
complex c1(5, 4), c2(2, 10), c3;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
c3 = c1 - c2; //使用重载运算符完成复数减法
cout << "c3=c1-c2=";
c3.display();
c3 = c1 + c2; //使用重载运算符完成复数加法
cout << "c3=c1+c2=";
c3.display();
}