一元运算符重载c ++

时间:2016-06-20 19:06:19

标签: c++ visual-studio oop operator-overloading

我在使用一元++重载运算符时遇到了麻烦。

这是我的代码......

 #include<iostream>

 using namespace std;

 class Index{

      int value;
 public:
     Index() : value(0) { }
     int GetIndex() const
     {
        return value;
     }
     void operator ++()
     {
        value++;
     }
};
int main()
{   
   Index idx1,idx2;

   ++idx1;
   idx2++;
   idx2++;

   cout << "idx1.value:" << idx1.GetIndex() << endl;
   cout << "idx2.value:" << idx2.GetIndex() << endl;


 }

语句idx2 ++给了我一个编译错误。然而前缀即++ idx1正常工作。我所指的书说两者都应该给出相同的输出...即值成员必须增加1。

为什么我会遇到这个问题?...我正在使用的IDE是visual studio 2015。

2 个答案:

答案 0 :(得分:2)

前缀和后缀++是两个独立的运算符。 C ++通过为后缀采用伪int参数和前缀没有参数来区分它们。

答案 1 :(得分:1)

https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

后缀增量运算符重载的签名是TYPE operator ++(int)

相关问题