如何以两种不同的方式为后缀 a++ 和前缀 ++a 重载运算符 ++? [重复]

问题描述 投票:0回答:5

如何以两种不同的方式为后缀

a++
和前缀
++a
重载运算符++?

c++ operator-overloading
5个回答
176
投票

应该看起来像这样:

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

35
投票

区别在于您为

operator ++
的过载选择什么签名。

引用自 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++
 
一般更有效。


18
投票
有两种方法可以重载类型 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 ;

t++ ;
 代码时,就会考虑它们: 

class T { // etc. } ; T & operator++(T & p_oRight) // ++A { // Do increment of p_oRight value return p_oRight ; } T operator++(T & p_oRight, int) // A++ { T oCopy ; // Copy p_oRight into oCopy // Do increment of p_oRight value return oCopy ; }

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

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

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

1
投票
像这样声明:

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

正确实施 - 不要搞乱每个人都知道他们所做的事情(先增加然后使用,使用然后增加)。


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

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

© www.soinside.com 2019 - 2024. All rights reserved.