C++中操作符重载自增\自减

来源:互联网 发布:发票认证软件叫什么 编辑:程序博客网 时间:2024/04/27 18:40

C++中操作符重载自增\自减_imaging_新浪博客
http://blog.sina.com.cn/s/blog_9ce5a1b501013618.html


你想过C++中操作符重载自增\自减时是怎样区分它的前缀和后缀形式的吗?

在句法上,重载函数是通过它们的参数类型的差异区分的,但是不管是前缀形式还是后缀形式的自增和自减都没有参数,我们到底该怎么区分它们呢?在开始时,C++在语法上面确实是存在这个问题的,程序员对此颇有微词。后来C++中加了一些特性来解决这个问题。

C++规定后缀形式有一个int类型的参数,当函数被调用时,编译器传递一个0作为int参数的值给该函数。

且看下面的小程序:

#include <iostream>

 

class MyInt{

    public:

    MyInt(int a):i(a) {   }

 

    MyInt& operator++();            // prefix ++

    const MyInt operator++(int);    // postfix ++

 

    MyInt& operator--();            // prefix --

    const MyInt operator--(int);    // postfix --

 

    friend std::ostream& operator<<(std::ostream&,const MyInt&);

 

    private:

    int i;

};

 

MyInt& MyInt::operator++()

{

    this->i++;

    return *this;

}

 

const MyInt MyInt::operator++(int)

{

    const MyInt temp = *this;

    ++(*this);

    return temp;

}

 

std::ostream& operator<<(std::ostream& out,const MyInt& t)

{

    out << t.i ;

    return out;

}

 

int main()

{

     MyInt a(0);

    

     a++;

     std::cout << a << std::endl; // i = 1,print 1

     ++a;

     std::cout << a << std::endl; // i = 2,print 2

 

     std::cout << a++ << std::endl; // i = 3,print 2

 

     std:: cout << ++a << std::endl; // i = 4,print 4

     return 0;

}

 

看上面的程序可以发现以下几点:

1.       后缀形式

0 0
原创粉丝点击