[英]How to overload the operator++ in two different ways for postfix a++ and prefix ++a?
如何以两种不同的方式为后缀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 };
PS:当我发现这个时,我最初看到的只是虚拟参数,但不同的返回类型实际上更有趣; 他们或许可以解释为什么++x
被认为比更高效的x++
一般。
您有两种方法可以为类型 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 ;
或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++)
};
正确实施 - 不要混淆每个人都知道他们所做的事情(先增加然后使用,使用然后增加)。
我知道已经晚了,但我遇到了同样的问题并找到了一个更简单的解决方案。 不要误会我的意思,这与上面的解决方案相同(由 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 方法中使用临时对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.