C++重载自增/减操作符

时间:2023-12-13 15:50:56

作为类成员使用。

前缀是先加/减1,再取值;后缀是先取值,再加/减1。

前缀是左值,返回引用;后缀是右值,返回值。

后缀多一个int参数进行区分,用时编译器会传个没用的0作实参。

在后缀实现中调用前缀版本。

可以显式调用:前缀 xxx.operator++(); 后缀 xxx.operator++(0)

#include <iostream>
#include <stdexcept> class CheckedPtr {
public:
// no default ctor
CheckedPtr(int* b, int *e) : beg(b), end(e), cur(b) {}
// prefix operators
CheckedPtr& operator++();
CheckedPtr& operator--();
// postfix operators
CheckedPtr operator++(int);
CheckedPtr operator--(int);
private:
int* beg;
int* end;
int* cur;
}; CheckedPtr& CheckedPtr::operator++()
{
if (cur == end) {
throw std::out_of_range("increment past the end of CheckedPtr");
}
++cur;
return *this;
} CheckedPtr& CheckedPtr::operator--()
{
if (cur == beg) {
throw std::out_of_range("decrement past the beginning of CheckedPtr");
}
--cur;
return *this;
} CheckedPtr CheckedPtr::operator++(int)
{
CheckedPtr ret(*this);
++*this;
return ret;
} CheckedPtr CheckedPtr::operator--(int)
{
CheckedPtr ret(*this);
--*this;
return ret;
} int main()
{
int ia[];
CheckedPtr parr(ia, ia+);
try {
parr++;
++parr;
parr.operator++();
parr.operator++();
}
catch (const std::out_of_range& e) {
std::cerr << e.what() << std::endl;
}
return ;
}