重载单目运算符(以++为例,前置和后置)

有一个time 类,包括数据成员minute ,sec模拟秒表,每次走一秒,满60秒进一分钟,此时秒从0起算

#include <iostream> 
using namespace std;
class Time 
{
    private ://私有数据成员 
    int sec;//秒
    int minute;//分 
    public://公有数据
    Time () {
        minute=0;
        sec=0;
    }//默认构造函数初始化
    Time (int a,int b) {
        minute=a;
        sec=b;//有参数的构造函数 
    }
    Time operator ++() ;//声明重载函数作为类成员函数
    void display () ;//声明输出函数 
    }; 
void Time::display() //类外定义输出函数 
{
    cout<<minute<<": "<<sec<<endl;
}
Time Time::operator++() 
{
    //类外定义重载函数
    if(++sec>=60) 
    {
        sec-=60;//秒位置发生变化
        ++minute;//分位置发生进位 
    }
  
 return *this;//!!!注意一定要返回this 指针 因为它的返回为一个类的对象所以要加星花
     
}
int main() 
{
    Time t(34,0);//建立一个类对象
    for(int i=0;i<61;i++) 
  {
      ++t;//使用重载后的符号
      t.display();//进行输出 
  }
    return 0;
 } 

前面重载了++运算符号,但是注意++分为前置和后置,它们的功能是不同的所以重载也有区别,c++系统会根据需要来调用不同的函数,接下来,我们看看后置++运算符怎么重载,以及和前置++的区别

#include <iostream> 
using namespace std;
class Time 
{
    private ://私有数据成员 
    int sec;//秒
    int minute;//分 
    public://公有数据
    Time () {
        minute=0;
        sec=0;
    }//默认构造函数初始化
    Time (int a,int b) {
        minute=a;
        sec=b;//有参数的构造函数 
    }
    Time operator ++(int) ;//声明重载函数作为类成员函数
    void display () ;//声明输出函数 
    }; 
void Time::display() //类外定义输出函数 
{
    cout<<minute<<": "<<sec<<endl;
}

Time Time::operator++(int) //不能用引用防止成为野指针 
{
    //类外定义重载函数
    Time temp(*this);//定义一个临时对象 
    sec++;
    if(sec>=60) 
    {
        sec-=60;//秒位置发生变化
        ++minute;//分位置发生进位 
    }
    return temp;//返回的是自加前的对象 
     
}
int main() 
{
    Time t(34,0),t2;//建立一个类对象
    cout<<"t";
    t.display();
    cout<<endl;
  t2=t++;//将自加前的对象值赋值
  cout<<"t2:"<<" " ;
  t2.display();
  cout<<endl;
  cout<<"t++";
  t.display(); 
    return 0;
 } 
可以看到后置自加运算符号多了int型的参数

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值