zoukankan      html  css  js  c++  java
  • C++学习笔记(5)----重载自增自减运算符

      自增运算符“++”和自减运算符“--”分别包含两个版本。即运算符前置形式(如 ++x)和运算符后置形式(如 x++),这两者进行的操作是不一样的。因此,当我们在对这两个运算符进行重载时,就必须区分前置和后置形式。C++根据参数的个数来区分前置和后置形式。如果按照通常的方法来重载 ++ 运算符(即作为成员函数重载时不带参数,或者作为非成员函数重载时带有一个参数),那么重载的是前置版本。要对后置形式进行重载,即 x++ 或 x--,就必须为重载函数再增加一个 int 类型的参数。该参数仅仅用来告诉编译器这是一个运算符后置形式,在实际调用时不需要给出实际的参数值。

    示例,定义一个重载了前置 ++ 和后置 ++ 运算符的 Integer 类:

    #include<iostream>
    using namespace std;
    
    class Integer {
    public :
        Integer(int num) {
            value = num;
        }
        Integer() {
            Integer(0);
        }
    
        friend ostream& operator <<(ostream& os, Integer& integer);
        
        Integer& operator ++()//前置形式
        {
            this->value++;
            return *this;
        }
    
        const Integer operator++(int)    //后置形式
        {
            Integer tmp(this->value);
            this->value++;
            return tmp;
        }
    
        int getValue() const;
        int setValue(int num);
    private:
        int value;
    };
    
    
    int Integer::getValue() const
    {
        return value;
    }
    int Integer::setValue(int num)
    {
        value = num;
        return value;
    }
    
    ostream& operator <<(ostream& os, Integer& integer)
    {
        os << integer.value;
        return os;
    }
    
    int main(int argc, char* argv[])
    {
        Integer num(10);
        cout << "num=" << num << endl;
        auto value = num++;
        cout << "num++=" << value << endl;
        cout << "now num=" << num << endl;
        value = ++num;
        cout << "++num=" << value << endl;
        
        return 0;
    }

    运行结果如下:

    S:Debug>string.exe
    num=10
    num++=10
    now num=11
    ++num=12
  • 相关阅读:
    php基础
    MYSQL 常用函数
    MYSQL 练习题
    MYSQL 查询
    MYSQL:增删改
    隐藏导航
    分层导航
    图片轮播!
    你帅不帅?
    PHP 流程
  • 原文地址:https://www.cnblogs.com/dongling/p/5737716.html
Copyright © 2011-2022 走看看