关于重载Time类的自增运算符++及注意点

#include<iostream>
using namespace std;
class Time
{
private:
    int hour,minute,second;
public:
    Time(int h,int m,int s);
    friend Time&operator++(Time &t);//返回引用是为了实现连续自增
    void display();
};
Time::Time(int h,int m,int s):hour(h),minute(m),second(s)
{
    if(hour>=24)hour=0;
    if(minute>=60)minute=0;
    if(second>=60)second=0;
}
void Time::display()
{
    cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Time &operator++(Time &t)
{
    ++t.second;
    if(t.second>=60)
    {
        t.second=0;
        ++t.minute;
        if(t.minute>=60)
        {
            t.minute=0;
            ++t.hour;
            if(t.hour>=24)t.hour=0;
        }
    }
    return t;
}
int main()
{
    Time t1(23,59,59);
    t1.display();
    ++t1;
    t1.display();
    return 0;

}

下面的这种情况则不能实现连续自增

#include<iostream>
using namespace std;
class Time
{
private:
    int hour,minute,second;
public:
    Time(int h,int m,int s);
    friend Time operator++(Time t);
    void display();
};
Time::Time(int h,int m,int s):hour(h),minute(m),second(s)
{
    if(hour>=24)hour=0;
    if(minute>=60)minute=0;
    if(second>=60)second=0;
}
void Time::display()
{
    cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Time operator++(Time t)
{
    ++t.second;
    if(t.second>=60)
    {
        t.second=0;
        ++t.minute;
        if(t.minute>=60)
        {
            t.minute=0;
            ++t.hour;
            if(t.hour>=24)t.hour=0;
        }
    }
    return t;
}
int main()
{
    Time t1(23,59,59);
    t1.display();
    t1=++t1;
    t1.display();
    return 0;
}
参考文献:C++.NET程序设计


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的复数complex的定义,其中重载了前置自增++”和后置自增++运算符和display函数: ```c++ #include <iostream> using namespace std; class complex { private: double real; // 实部 double imag; // 虚部 public: // 构造函数 complex(double r = 0, double i = 0) : real(r), imag(i) {} // 前置自增运算符 ++ complex operator++() { real++; // 实部加 1 imag++; // 虚部加 1 return *this; } // 后置自增运算符 ++ complex operator++(int) { complex tmp(*this); operator++(); // 调用前置自增运算符 return tmp; } // 显示复数 void display() const { cout << "(" << real << ", " << imag << "i)" << endl; } }; ``` 在上面的代码中,我们定义了一个复数`complex`,包含了实部`real`和虚部`imag`两个私有成员变量。为了方便使用,我们提供了一个构造函数,可以用来创建复数对象。同时,我们还重载了前置自增++”和后置自增++运算符,使得我们可以对复数对象进行自增操作。最后,我们还提供了一个`display`函数,用来显示复数对象的值。 下面是一个简单的测试代码,用来测试我们刚才定义的复数: ```c++ int main() { complex a(1, 2); a.display(); // 显示 (1, 2i) ++a; a.display(); // 显示 (2, 3i) a++; a.display(); // 显示 (3, 4i) return 0; } ``` 在测试代码中,我们创建了一个复数对象`a`,并且调用了它的`display`函数,将其值显示出来。然后,我们对它进行了两次自增操作,分别使用了前置自增++”和后置自增++运算符,最后再次调用`display`函数,将其最新的值显示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值