首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为前增量和后增量重载++

为前增量和后增量重载++
EN

Stack Overflow用户
提问于 2013-03-06 17:58:54
回答 4查看 64.3K关注 0票数 57

我们可以为增量前和增量后重载operator++吗?例如,调用SampleObject++++SampleObject会给出正确的结果。

代码语言:javascript
复制
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; */
    } */
};

我们不能仅仅基于返回类型来重载一个函数,而且即使我们认为它是允许的,它也不能解决问题,因为重载解析中的歧义。

既然提供了操作符重载,以使内置类型的行为像用户定义的类型,为什么我们不能同时使用我们自己的类型的前增量和后增量?

EN

回答 4

Stack Overflow用户

发布于 2013-03-06 18:02:44

增量运算符的后缀版本接受一个伪int参数,以消除歧义:

代码语言:javascript
复制
// prefix
CSample& operator++()
{
  // implement increment logic on this instance, return reference to it.
  return *this;
}

// postfix
CSample operator++(int)
{
  CSample tmp(*this);
  operator++(); // prefix-increment this instance
  return tmp;   // return value before increment
}
票数 101
EN

Stack Overflow用户

发布于 2013-03-06 20:29:10

类型T的前增量和后增量的标准模式

代码语言:javascript
复制
T& T::operator++() // pre-increment, return *this by reference
{
 // perform operation


 return *this;
}

T T::operator++(int) // post-increment, return unmodified copy by value
{
     T copy(*this);
     ++(*this); // or operator++();
     return copy;
}

(您也可以调用一个公共函数来执行递增,或者如果它是一个简单的一行程序,比如成员上的++,那么只需在这两个函数中都执行)

票数 26
EN

Stack Overflow用户

发布于 2013-03-06 18:06:06

为什么我们不能对我们自己的类型同时使用前增量和后增量。

您可以:

代码语言:javascript
复制
class CSample {
public:

     int m_iValue;
     CSample() : m_iValue(0) {}
     CSample(int val) : m_iValue(val) {}

     // Overloading ++ for Pre-Increment
     int /*CSample& */ operator++() {
        ++m_iValue;
        return m_iValue;
     }

    // Overloading ++ for Post-Increment
    int operator++(int) {
          int value = m_iValue;
          ++m_iValue;
          return value;
      }
  };

  #include <iostream>

  int main()
  {
      CSample s;
      int i = ++s;
      std::cout << i << std::endl; // Prints 1
      int j = s++;
      std::cout << j << std::endl; // Prints 1
  }
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15244094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档