c++ - 按时使用重载运算符

标签 c++ operator-overloading

我已经上了这个半笔试课。

using namespace std;

#include <iostream>
#include <iomanip>
#include "Time.h"

Time::Time()
{ hour = min = sec = 0;
}

Time::Time(int h, int m, int s)
{ setTime(h, m, s);
}

void Time::setTime(int h, int m, int s)
{ hour = (h>=0 && h<24) ? h : 0;
  min = (m>=0 && m<60) ? m : 0;
  sec = (s>=0 && s<60) ? s : 0;
}

Time& Time::operator+=(unsigned int n)
{ sec += n;
  if (sec >= 60)
  { min += sec/60;
    sec %= 60;
    if (min >=60)
    { hour = (hour + min/60) % 24;
      min %= 60;
    }
  }
  return *this;
}

Time Time::operator+(unsigned int n) const
{ Time tCopy(*this);
  tCopy += n;
  return tCopy;
}

Time& Time::operator++()        // prefix version
{ *this += 1;
  return *this;
}

Time Time::operator++(int n)    // postfix version
{ Time tCopy(*this);
  *this += 1;
  return tCopy;
}

ostream& operator<<(ostream &o, const Time &t)
{ o << setfill('0') << setw(2) <<  t.hour << ':' << setw(2) << t.min << ':' << setw(2) << t.sec;
  return o;
}

和这个头文件,

// using _TIMEX_H_ since _TIME_H_ seems to be used by some C++ systems

#ifndef _TIMEX_H_
#define _TIMEX_H_

using namespace std;

#include <iostream>

class Time
{ public:
    Time();
    Time(int h, int m = 0, int s = 0);
    void setTime(int, int, int);
    Time operator+(unsigned int) const;
    Time& operator+=(unsigned int);
    Time& operator++();    // postfix version
    Time operator++(int);  // prefix version

    // new member functions that you have to implement

    Time operator-(unsigned int) const;
    Time& operator-=(unsigned int);
    Time& operator--();      // postfix version
    Time operator--(int);  // prefix version

    bool operator==(const Time&) const;
    bool operator<(const Time&) const;
    bool operator>(const Time&) const;

  private:
    int hour, min, sec;

  friend ostream& operator<<(ostream&, const Time&);

  // new friend functions that you have to implement

  friend bool operator<=(const Time&, const Time&);
  friend bool operator>=(const Time&, const Time&);
  friend bool operator!=(const Time&, const Time&);

  friend unsigned int operator-(const Time&, const Time&);
};

#endif

我想我可以实现其他运算符函数和友元函数,但是我在编写一个主要方法来测试它当前的工作方式时遇到了麻烦,我才刚刚开始学习 C++,我真的很吃力所以很抱歉不知道如何写这个。提前致谢。

最佳答案

测试重载运算符没有什么特别之处。 只需在 main 中创建 2 个对象并编写如下内容:

Time t1(10,20,30),t2(1,2,3);

现在,为了检查 += 运算符,写:

t1+=10;

您的重载函数将被自动调用,您也可以添加 2 个对象而不是数字,如下所示:

t1+=t2;

唯一的区别是参数,而不是 int,它将是 Time 类型的对象。

要检查 << 运算符,只需编写:

cout<<t1;

其余的将由 friend 函数处理。

希望这对您有所帮助。

关于c++ - 按时使用重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611319/

相关文章:

C++ 创建模板 T 对象的拷贝

c++ - 运算符在类中定义为 friend 的奇怪行为

operator-overloading - 覆盖/重载 + 运算符以对常见的 lisp 向量进行操作

c++ - 如何更新一组 std::pair 中的成员?

c++ - 快速解析和打印 Google Protobuf 的方法

c++ - h264 ffmpeg : How to initialize ffmpeg to decode NALs created with x264

c++ - 无法在 DirectX11 上创建一维纹理

C++竞技编程: Simplifying expressions under modulo N

c++ - 以自定义类作为键的 std::map 始终返回 1 的大小

c++ - 如何将 std::map 初始化为类成员