如何以两种不同的方式为后缀
a++
和前缀++a
重载运算符++?
应该看起来像这样:
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.
}
};
区别在于您为
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++
一般更有效。
对象方法:
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 接口的一部分(只要它们位于同一命名空间中)。
非成员函数表示法有两个潜在的优点:
class A
{
public:
A& operator++(); //Prefix (++a)
A operator++(int); //Postfix (a++)
};
正确实施 - 不要搞乱每个人都知道他们所做的事情(先增加然后使用,使用然后增加)。
一点。一点点。这是:
class Number
{
public:
/*prefix*/
Number& operator++ ()
{
/*Do stuff */
return *this;
}
/*postfix*/
Number& operator++ (int)
{
++(*this); //using the prefix operator from before
return *this;
}
};