C++操作符重载-------类成员操作符重载

1. 语法

返回类型 类名::operator 操作符(形参表)

{

函数体代码;

}

2. 实例

#include <iostream>
#include <ctime>

using namespace std;
class StopWatch{
public:
    StopWatch();//构造函数
    void setTime(int newMin,int newSec);//设置秒表时间
    StopWatch operator - (StopWatch&);//计算两个秒表的时间
    void showTime();
private:
    int min;
    int sec;
};

StopWatch::StopWatch()
{
    min=0;
    sec=0;
}

void StopWatch::setTime(int newMin,int newSec)
{
    min=newMin;
    sec=newSec;
}

StopWatch StopWatch::operator - (StopWatch& anotherTime)
{
    StopWatch tempTime;
    int seconds;//两个秒表时间间隔的秒数

    seconds=min*60+sec-(anotherTime.min*60+anotherTime.sec);
    if(seconds<0)
        seconds=-seconds;
    tempTime.min=seconds/60;
    tempTime.sec=seconds%60;
    return tempTime;
}

void StopWatch::showTime()
{
    if(min>0)
        cout<<min<<"minutes"<<sec<<"seconds\n";
    else
        cout<<sec<<"seconds\n";

}

int main()
{
    StopWatch startTime,endTime,usedTime;
    cout<<"按回车开始!";
    cin.get();//等待用户输入
    time_t curtime=time(0);//获取当前系统时间
    tm tim=*localtime(&curtime);//根据当前时间获取当地时间
    int min,sec;
    min=tim.tm_min;//得到当地时间的分
    sec=tim.tm_sec;//得到当地时间的秒
    startTime.setTime(min,sec);
    cout<<"按回车结束!";
    cin.get();//等待输入
    curtime=time(0);
    tim=*localtime(&curtime);
    min=tim.tm_min;
    sec=tim.tm_sec;
    endTime.setTime(min,sec);

    usedTime=endTime-startTime;
    cout<<"用时。。。";
    usedTime.showTime();
    return 0;
}

  其中包含以下信息

a. 函数名是operator —,表示重载操作符 -;

  b. StopWatch::表示重载该操作符的类是StopWatch类;

  c. 该函数返回类型是StopWatch类型

  d. 该函数带一个参数,参数类型是StopWatch类,并以引用的形式传。