C++:为前后增量重载 ++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15244094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:12:25  来源:igfitidea点击:

C++: overloading ++ for both pre and post increment

c++operator-overloading

提问by null

Can we overload operator++for pre-increment and post-increment? i.e. calling SampleObject++and ++SampleObjectresults correctly.

我们可以重载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; */
    } */
};

We can't overload a function based only on return type, and also even if we take it as permitted, it doesn't solve the problem because of the ambiguity in call resolution.

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

Since operator overloading is provided to make built-in types behave like as user-defined types, why we can't avail both pre and post increment for our own types at the same time.

由于提供了运算符重载以使内置类型的行为类似于用户定义的类型,为什么我们不能同时为我们自己的类型使用前置和后置增量。

回答by juanchopanza

The postfix version of the increment operator takes a dummy intparameter in order to disambiguate:

增量运算符的后缀版本采用一个虚拟int参数来消除歧义:

// 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
}

回答by CashCow

The standard pattern for pre-increment and post-increment for type T

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

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;
}

(You can also call a common function for performing the increment, or if it's a simple one-liner like ++ on a member, just do it in both)

(您也可以调用一个通用函数来执行增量,或者如果它是一个简单的单行函数,例如成员上的 ++,则在两者中都执行)

回答by Andy Prowl

why we can't avail both pre and post increment for our own types at the same time.

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

You can:

你可以:

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
  }

回答by u6949852

[N4687]

[N4687]

16.5.7

16.5.7

The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a non-static member function with no parameters, or a non-member function with one parameter, it defines the prefix increment operator++ for objects of that type. If the function is a non-static member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero

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

Example:

例子:

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++;
}

回答by Aayush Kumar

#include<iostream>
using namespace std;

class increment{
int a;
public:
increment(int x)
{ a=x; }

void operator ++(){
cout<<"pre-increment:";
cout<<++a;}

void operator ++(int){                  /*post version of increment operator takes  int as a dummy parameter*/

 cout<<endl<<"post-increment:";
 cout<<a++;}
};


int main(){
increment o1(4);   
increment o2(4);
++o1;       //pre-increment
o2++;       //post-increment

}

OUTPUT:
pre-increment:5
post-increment:4

输出:
前增量:5
后增量:4