[置顶] c++重载自增和自减操作符

时间:2022-07-29 17:48:18
#include<iostream>
#include<cstdlib>

using namespace std;

class Pair{
public:
Pair(int firstPart, int secondPart);
Pair operator++();
Pair operator++(int);
void setFirstPart(int firstPart);
void setSecondPart(int secondPart);
int getFirstPart() const;
int getSecondPart() const;

private:
int firstPart;
int secondPart;
};

int main(){
Pair a(1, 2);
cout<<"Postfix a++:";
cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
Pair b = a++;
cout<<"Postfix b++:";
cout<<b.getFirstPart()<<" "<<b.getSecondPart()<<endl;
cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;

a = Pair(1, 2);
cout<<"Prefix ++a:";
cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
Pair c = ++a;
cout<<"Postfix c++:";
cout<<c.getFirstPart()<<" "<<c.getSecondPart()<<endl;
cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
}

Pair::Pair(int firstPart, int secondPart):firstPart(firstPart),secondPart(secondPart){

}
Pair Pair::operator++(){
firstPart++;
secondPart++;
return Pair(firstPart, secondPart);
}

Pair Pair::operator++(int flag){
int temp1 = firstPart;
int temp2 = secondPart;
firstPart++;
secondPart++;
return Pair(temp1, temp2);
}

int Pair::getFirstPart() const{
return firstPart;
}

int Pair::getSecondPart() const{
return secondPart;
}

void Pair::setFirstPart(int firstPart){
this->firstPart= firstPart;
}

void Pair::setSecondPart(int secondPart){
this->secondPart = secondPart;
}
上面是重载自增操作符的代码,自减操作符类似。注意:在后缀自增的重载函数里面的一个int类型的参数只是作为编译器的一个标志,在函数中并没有用到。