C++语言基础 例程 重载单目运算符

时间:2021-09-29 02:13:50

贺老师的教学链接  本课讲解


示例1:分数类对象的相反数

class CFraction{
private:
int nume; // 分子
int deno; // 分母
public:
CFraction(int nu=0,int de=1):nume(nu),deno(de) {}
CFraction operator-(const CFraction &c); //两个分数相减,结果要化简
CFraction operator-(); //取反一目运算
};

// 分数相减
CFraction CFraction:: operator-(const CFraction &c)
{
CFraction t;
t.nume=nume*c.deno-c.nume*deno;
t.deno=deno*c.deno;
t.simplify();
return t;
}

// 分数取负号
CFraction CFraction:: operator-()
{
CFraction x;
x.nume=-nume;
x.deno=deno;
return x;
}


案例:Time类的++

#include <iostream>using namespace std;class Time{public:    Time( )    {        minute=0;        sec=0;    }    Time(int m,int s):minute(m),sec(s) { }    Time operator++( );    Time operator++(int);    void display( )    {        cout<<minute<<":"<<sec<<endl;    }private:    int minute;    int sec;};Time Time::operator++( ){    if(++sec>=60)    {        sec-=60;        ++minute;    }    return *this;} Time Time::operator++(int){    Time temp(*this);    sec++;    if(sec>=60)    {        sec-=60;        ++minute;    }    return temp;} int main( ){    Time time1(34,59),time2;    cout<<" time1 : ";    time1.display( );    ++time1;    cout<<"++time1: ";    time1.display( );    time2=time1++;          //将自加前的对象的值赋给time2    cout<<"time1++: ";    time1.display( );    cout<<" time2 :";    time2.display( );          //输出time2对象的值    return 0;}