为了账号安全,请及时绑定邮箱和手机立即绑定

c++的重载运算符问题

c++的重载运算符问题

C++
慕粉18341035298 2016-12-24 21:16:35
#include<iostream> #include<algorithm> #include<iomanip> #include<cmath> #include<string.h> #include<stdlib.h> #include<sstream> #include<cmath> using namespace std; class clock{ private:  int hour, minute, second; public:  clock(int h = 0, int m = 0, int s = 0);  void show();  clock operator++(); }; clock::clock(int h, int m, int s){  hour = h;  minute = m;  second = s; } void clock::show(){  cout << hour << ":" << minute << ":" << second << endl; } clock clock::operator++() {  second++;  if (second == 60){   second -= 60;   minute++;   if (minute == 60){    minute -= 60;    hour++;    hour %= 24;   }  }  return *this; } int main() {  clock ck(18, 59, 58), a;  ck.show();  a = ck++;  a.show();  return 0; }我按照书敲得,可还是通过不了,书有好多错误。。。求助改法谢谢
查看完整描述

1 回答

?
onemoo

TA贡献883条经验 获得超454个赞

operator++() 这样重载的是 prefix 版本的自增运算符,也就是这样调用的 ++ck。而且它的返回类型应该是clock引用。

如果重载 postfix 版本的自增运算符,要加上一个不使用的int类型参数: operator++(int)

看这个函数中的逻辑,应该重载的是 prefix 版本。

查看完整回答
反对 回复 2016-12-24
  • 1 回答
  • 0 关注
  • 1295 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信