如何以两种不同的方式为operator + ++和前缀++ a重载operator ++?

时间:2010-10-02 15:09:56

标签: c++ operator-overloading

如何以两种不同的方式为operator a++和前缀++a重载operator ++?

5 个答案:

答案 0 :(得分:154)

应该是这样的:

class Number 
{
    public:
        Number& operator++ ()     // prefix ++
        {
           // Do work on this.   (increment your object here)
           return *this;
        }

        // You want to make the ++ operator work like the standard operators
        // The simple way to do this is to implement postfix in terms of prefix.
        //
        Number  operator++ (int)  // postfix ++
        {
           Number result(*this);   // make a copy for result
           ++(*this);              // Now use the prefix version to do the work
           return result;          // return the copy (the old) value.
        }
}; 

答案 1 :(得分:32)

区别在于您为operator ++的重载选择的签名。

引自相关的article on this subject in the C++ FAQ(去那里了解更多详情):

class Number {
  public:
    Number& operator++ ();     // prefix ++: no parameter, returns a reference
    Number  operator++ (int);  // postfix ++: dummy parameter, returns a value
};

P.S。:当我发现这一点时,我最初看到的只是虚拟参数,但不同的返回类型实际上更有趣;他们可能会解释为什么++x被认为比一般中的x++ 更有效。

答案 2 :(得分:16)

有两种方法可以为类型T重写两个(前缀/后缀)++运算符:

对象方法:

这是最简单的方法,使用“常见的”OOP习语。

class T
{
    public :
        T & operator++() // ++A
        {
            // Do increment of "this" value
            return *this ;
        }

        T operator++(int) // A++
        {
           T temp = *this ;
           // Do increment of "this" value
           return temp ;
        }
} ;

对象非成员函数:

这是另一种方法:只要函数与它们引用的对象在同一名称空间中,当编译器搜索函数来处理++t ;或{时,将考虑它们。 {1}}代码:

t++ ;

重要的是要记住,从C ++的角度来看(包括C ++编译器的观点),那些非成员函数仍然是T接口的一部分(只要它们在同一名称空间中)。

非成员函数表示法有两个潜在的优点:

  • 如果你设法对它们进行编码而不使它们成为T的朋友,那么你就增加了T
  • 的封装
  • 您甚至可以将其应用于您不拥有其代码的类或结构。这是一种非侵入性的方法来增强对象的接口而不修改其声明。

答案 3 :(得分:1)

声明如下:

class A
{
public:
    A& operator++();    //Prefix (++a)
    A operator++(int); //Postfix (a++)

};

正确实施 - 不要弄乱每个人都知道的事情(增加然后使用,然后使用增量)。

答案 4 :(得分:-1)

我知道它已经很晚了,但我遇到了同样的问题并找到了一个更简单的解决方案。不要误会我的意思,这是与前者相同的相同解决方案(由Martin York发布)。它只是一个更简单。一点点。这是:

class Number
{
        public:

              /*prefix*/  
        Number& operator++ ()
        {
            /*Do stuff */
            return *this;
        }

            /*postfix*/
        Number& operator++ (int) 
        {
            ++(*this); //using the prefix operator from before
            return *this;
        }
};

上述解决方案稍微简单一些,因为它在后缀方法中没有使用临时对象。