C++类的运算符重载

C++类运算符重载是一种方便的语法,例如可以执行两个类相加

Time sum = time1 + time2;

类的运算符重载语法如下

operator(args-list);
class Time
{
    private:
        int hours;
        int minutes;
    public:
        Time operator+(const Time & t) const;
};

Time Time::operator+(const Time &t) const
{
    Time sum;
    int minutes_sum = minutes + t.minutes;
    sum.hours = hours + t.hours + minutes_sum / 60;
    sum.minutes = minutes_sum % 60;
}

你可能感兴趣的:(C++类的运算符重载)