前后增量的重载

新手上路,请多包涵

我们可以超载 operator++ 用于前增量和后增量吗?即调用 SampleObject++++SampleObject 给出正确的结果。

 class CSample {
 public:
   int m_iValue;     // just to directly fetch inside main()
   CSample() : m_iValue(0) {}
   CSample(int val) : m_iValue(val) {}
   // Overloading ++ for Pre-Increment
   int /*CSample& */ operator++() { // can also adopt to return CSample&
      ++(*this).m_iValue;
      return m_iValue; /*(*this); */
   }

  // Overloading ++ for Post-Increment
 /* int operator++() {
        CSample temp = *this;
        ++(*this).m_iValue;
        return temp.m_iValue; /* temp; */
    } */
};

我们不能只根据返回类型重载一个函数,而且即使我们认为它是允许的,由于重载决策的模糊性,它也不能解决问题。

既然提供了运算符重载来使内置类型表现得像用户定义的类型,为什么我们不能同时为我们自己的类型使用前置和后置增量呢?

原文由 null 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 469
1 个回答

[N4687]

16.5.7

名为 operator++ 的用户定义函数实现了前缀和后缀 ++ 运算符。如果这个函数是一个没有参数的非静态成员函数,或者一个有一个参数的非成员函数,它为该类型的对象定义了前缀自增运算符++。如果函数是具有一个参数的非静态成员函数(应为 int 类型)或具有两个参数的非成员函数(第二个应为 int 类型),则定义后缀递增运算符 ++对于该类型的对象。当使用 ++ 运算符调用后缀增量时,int 参数的值为零

例子:

 struct X {
  X&   operator++();    // prefix ++a
  X    operator++(int); // postfix a++
};

struct Y { };

Y&   operator++(Y&);      // prefix ++b
Y    operator++(Y&, int); // postfix b++

void f(X a, Y b) {
  ++a; // a.operator++();
  a++; // a.operator++(0);
  ++b; // operator++(b);
  b++; // operator++(b, 0);

  a.operator++();     // explicit call: like ++a;
  a.operator++(0);    // explicit call: like a++;
  operator++(b);      // explicit call: like   ++b;
  operator++(b, 0);   // explicit call: like b++;
}

原文由 Chen Li 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题