1

可能重复:
运算符重载

“你需要实现一个名为 Duration 的类,它表示时间长度,以小时、分钟和秒表示,例如 CD 上曲目的长度,或跑马拉松所用的时间。该类应该具有一组适当的构造函数(包括错误检查)和访问器方法。其中一个构造函数应允许使用单个整数初始化 Duration 对象,以秒为单位表示持续时间。应重载 << 和 >> 运算符以允许Duration 对象通过流的输入和输出。Duration 对象应以 \h:mm:ss" 格式输出,例如 \1:39:33"、\0:09:07" 和 \1:00:08"。此外,加法运算符 + 应该被重载,以便可以将两个 Duration 对象相加以生成新的 Duration 对象,并且可以将整数秒数添加到 Duration 对象中。最后,该类应该定义从 Duration 对象到表示持续时间(以秒为单位)的整数的类型转换。”

    #include <iostream>
    #include <stdlib.h>
    using namespace std;
    using std::cout;
    using std::cin;
    using std::ostream;
    using std::istream;

    class Duration 
    {
        private:
        int hours, minutes, seconds;
        int theSeconds;

        public:
        Duration() //default constructor.
        {}

        Duration(int hr, int min, int sec) //ordinary constructor.
        {
            hours = hr;
            minutes = min;
            seconds = sec;
        }

        inline int getHours()
        {
            return hours;
        }

        inline int getMinutes()
        {
            return minutes;
        }

        inline int getSeconds()
        {
            return seconds;
        }
    };

希望到目前为止我已经朝着正确的方向完成了这项任务(本周对 c++ 来说是新的)。但是,我正在努力解决如何实现我以粗体突出显示的部分以及之后的所有内容......

请建议和帮助我。另请注意,这不是课程作业等。我只是想为明年的 C++ 做准备。谢谢你。

4

1 回答 1

1

你应该有一个这样std::ostream &实现的 -returning 函数:

class Duration {

    int hours, minutes, seconds;
    int theSeconds;

    public:

        friend std::ostream & operator << (std::ostream & os, const Duration & dObj) {

            os << "The hours are " << dObj.hours << '\n';
            os << "The minutes are " << dObj.minutes << '\n';

            // ... and so on

        }

        Duration() {}
        Duration(int hr, int min, int sec) {
            hours = hr;
            minutes = min;
            seconds = sec;
    }

};

你也可以operator>>用同样的方式定义:

friend std::istream & operator >> ( std::ostream & os, const Duration dObj ) {

    os >> dObj.minutes >> dObj.hours /* >> ... */;

    return os;

}

所以你可以像这样使用它:

Duration d;

std::cin >> d;

std::cout << d;
于 2012-11-01T18:41:04.530 回答