C ++前后增量

时间:2014-03-25 21:17:52

标签: c++ operator-overloading post-increment pre-increment

我在重载后增量方法时遇到问题 我的预增量很好 我也有前/后减量,它们都很完美。
增量和减量体应该相似。唯一的区别应该是++ / - ,但我不确定为什么我的帖子增量不会像我的帖子减量那样起作用。

预增量

upDate upDate::operator++() {
   int julian = convertDateToJulian(datePtr[0], datePtr[1], datePtr[2]);
   julian++;
   convertDateToGregorian(julian);
   return (*this);
}

后增量

upDate upDate::operator++(int num) {
   upDate temp (*this);
   int julian = convertDateToJulian(datePtr[0], datePtr[1], datePtr[2]);
   julian++;
   convertDateToGregorian(julian);
   return temp;
} 

减刑后

upDate upDate::operator--(int num) {
   upDate temp(*this);
   int julian = convertDateToJulian(datePtr[0], datePtr[1], datePtr[2]);
   julian--;
   convertDateToGregorian(julian);
   return temp;
}

这是我的主要内容:

upDate d5(11, 10, 2004);
++d5;
cout << d5 << endl;
cout << "Expected November 11, 2004\n" << endl;

//not working
upDate d6(11, 11, 2004);
d5++;
cout << d6 << endl;
cout << "Expected November 12, 2004\n" << endl;

upDate d11(12, 3, 1992);
d11--;
cout << d11 << endl;
cout << "Expected: December 2, 1992\n" << endl;

输出结果为:
//日期原定于2004年11月10日
// ++增量
2004年11月11日
预计:2004年11月11日

//日期原定于2004年11月11日
//增量++
2004年11月11日//输出不应该是这个 预计:2004年11月12日

//日期最初是1992年12月2日 // decr--
1992年12月1日 预计:1992年12月1日

2 个答案:

答案 0 :(得分:1)

你的主要输入错误:

//not working
upDate d6(11, 11, 2004);
d6++;  // <---- you have d5++;
cout << d6 << endl;
cout << "Expected November 12, 2004\n" << endl;

答案 1 :(得分:0)

你有一个错字。在此代码段中

//not working
upDate d6(11, 11, 2004);
d5++;
cout << d6 << endl;
cout << "Expected November 12, 2004\n" << endl;

您将后增量运算符应用于 d5

d5++;

但是输出 d6

cout << d6 << endl;

d6没有改变。

还要考虑到预增量运算符的正确声明是

upDate & upDate::operator++();

当操作员返回临时对象时,操作员应返回左值。

相关问题