【问题标题】:unary operator overloading c++ [duplicate]一元运算符重载c ++ [重复]
【发布时间】:2016-06-20 19:06:18
【问题描述】:

我在使用一元 ++ 重载运算符时遇到问题。

这是我的代码...

 #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 工作正常。我所指的书说两者都应该给出相同的输出......即 value 成员必须增加1.

为什么我会遇到这个问题??...我使用的 IDE 是 Visual Studio 2015。

【问题讨论】:

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


【解决方案1】:

前缀和后缀 ++ 是两个独立的运算符。 C++ 通过为后缀使用虚拟 int 参数而对前缀不使用参数来区分它们。

【讨论】:

  • 谢谢...我知道了
【解决方案2】:

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

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

【讨论】:

  • 感谢您的链接...
猜你喜欢
  • 2011-10-27
  • 2012-12-22
  • 2016-09-26
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2010-10-21
相关资源
最近更新 更多