跳到内容

重载示例:Time类 ​

用普通方法做加法 ​

为了看清"为什么要重载",先看一个用普通方法做时间相加的版本。Time 类记录小时和分钟:

cpp
// timev0.h
#ifndef TIMEV0_H_
#define TIMEV0_H_

class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m = 0);
    void addMin(int m);
    void addHr(int h);
    void reset(int h = 0, int m = 0);
    Time sum(const Time& t) const;     // 普通方法:返回相加结果
    void show() const;
};

#endif
cpp
// timev0.cpp
#include <iostream>
#include "timev0.h"

Time::Time() : hours(0), minutes(0) {}
Time::Time(int h, int m) : hours(h), minutes(m) {}

void Time::addMin(int m)
{
    minutes += m;
    hours += minutes / 60;
    minutes %= 60;
}

void Time::addHr(int h) { hours += h; }

void Time::reset(int h, int m) { hours = h; minutes = m; }

Time Time::sum(const Time& t) const
{
    Time result;
    result.minutes = minutes + t.minutes;
    result.hours = hours + t.hours + result.minutes / 60;
    result.minutes %= 60;
    return result;
}

void Time::show() const
{
    std::cout << hours << " 时 " << minutes << " 分";
}

调用时是 total = a.sum(b);——能工作,但读起来像"调用方法",不像"相加"。

改成 operator+ ​

把 sum 换成 operator+,逻辑完全一样,只是换了个名字:

cpp
// timev1.h
#ifndef TIMEV1_H_
#define TIMEV1_H_

class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int h, int m = 0);
    void addMin(int m);
    void addHr(int h);
    void reset(int h = 0, int m = 0);
    Time operator+(const Time& t) const;   // 重载 +
    Time operator-(const Time& t) const;   // 重载 -
    Time operator*(double n) const;        // 重载 *(时间乘以倍数)
    void show() const;
};

#endif
cpp
// timev1.cpp
#include <iostream>
#include "timev1.h"

Time::Time() : hours(0), minutes(0) {}
Time::Time(int h, int m) : hours(h), minutes(m) {}

void Time::addMin(int m)
{
    minutes += m;
    hours += minutes / 60;
    minutes %= 60;
}

void Time::addHr(int h) { hours += h; }
void Time::reset(int h, int m) { hours = h; minutes = m; }

Time Time::operator+(const Time& t) const
{
    Time result;
    result.minutes = minutes + t.minutes;
    result.hours = hours + t.hours + result.minutes / 60;
    result.minutes %= 60;
    return result;
}

Time Time::operator-(const Time& t) const
{
    Time diff;
    int tot1 = t.minutes + 60 * t.hours;
    int tot2 = minutes + 60 * hours;
    diff.minutes = (tot2 - tot1) % 60;
    diff.hours = (tot2 - tot1) / 60;
    return diff;
}

Time Time::operator*(double n) const
{
    long totalMin = hours * 60 * n + minutes * n;
    return Time(totalMin / 60, totalMin % 60);
}

void Time::show() const
{
    std::cout << hours << " 时 " << minutes << " 分";
}

现在 a + b、a - b、a * 1.5 都能直接写:

cpp
#include <iostream>
#include "timev1.h"

int main()
{
    Time a(3, 45);
    Time b(2, 30);
    Time total = a + b;        // 6 时 15 分
    Time gap = a - b;          // 1 时 15 分
    Time scaled = a * 2.0;     // 7 时 30 分
    std::cout << "相加: "; total.show();  std::cout << "\n";
    std::cout << "相减: "; gap.show();    std::cout << "\n";
    std::cout << "翻倍: "; scaled.show(); std::cout << "\n";
    return 0;
}

为什么返回值是按值返回 ​

注意 operator+ 的返回类型是 Time(不是 Time&)。原因:相加产生的是一个新对象,它只在函数内部存在。如果返回引用,就会引用一个函数返回时已销毁的局部对象——悬垂引用,未定义行为。返回新类型对象时按值返回;返回已存在的对象(如 operator= 返回 *this、operator<< 返回流)时才返回引用。

为什么参数是 const 引用 ​

operator+(const Time& t) 的参数用 const 引用:

  • 引用:避免拷贝整个对象,省开销。
  • const:承诺不改它,也让 const 对象能作为右操作数。

左操作数(调用对象)不需要作为参数写出来——它是隐式的 this。但因为运算符不修改左操作数,整个函数加了 const。

重载的局限与下一站 ​

现在 a + b 和 a * 2.0 都能用。但 2.0 * a 不行——因为左操作数是 double,而成员函数要求左操作数是 Time。要支持"左操作数不是本类"的情形,需要非成员函数,也就是下一节要讲的友元。

同样,想用 std::cout << a 直接打印 Time,<< 的左操作数是 std::ostream,也必须靠非成员(友元)函数实现。

课后练习 ​

  1. 从方法到运算符:把上一节 Lamp 类的某个"比较亮度"方法改写成 operator<,让两个 Lamp 能直接用 < 比较。测试 if (l1 < l2) ...。
  2. 重载减法:仿照 Time::operator+,给 Time 加一个 operator-,求两个时间之差(确保结果不为负时也合理)。测试 a - b 和 b - a。
  3. 倍数运算:给 Time 重载 operator*(double n),表示时长放大 n 倍。测试 a * 2.5,确认进位正确。
  4. 返回类型辨析:解释为什么 Time::operator+ 返回 Time 而不是 Time&;再写一个会修改自身的 operator+=,思考它该返回 Time& 还是 Time,并说明理由(提示:复合赋值通常返回 *this 的引用)。