C ++ overload auto-increment and auto-subtraction Operators

Source: Internet
Author: User
#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;}

The above is the code for reloading the auto-increment operator. The auto-increment operator is similar. Note: an int type parameter in an auto-increment function with a suffix is only a sign of the compiler and is not used in the function.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.