zoukankan      html  css  js  c++  java
  • 自增运算符重载

    //前置++是把对象加1后再给你用。

    //后置++是把对象的值借你用,再把对象本身加1。


    1.作为成员函数:

    前缀自增运算符

        test operator++() //前置运算符
        {
            this->value++;
            return *this;
        }

    后缀自增运算符

        test operator++(int) //后置运算符
        {
            test temp(*this);  //将对象的值赋给临时建立的对象
            this->value++;
            return temp;       //返回临时建立的对象,
        }



    2.作为友元函数:

    先要在类内声明友元函数

        friend test operator++(test& a);
        friend test operator++(test& a,int);
    然后再类外定义

    test operator++(test& a) //前置运算符
    {
        a.value++;
        return a;
    }
    
    test operator++(test& a,int) //后置运算符
    {
        test temp(a);
        a.value++;
        return temp;
    }
    





    代码:


    #include <iostream>
    #include <string>
    
    using namespace std;
    
    //前置++是把对象加1后再给你用
    //后置++是把对象的值借你,再把对象本身加1
    
    
    class test
    {
        int value;
    public:
        test():value(0){}      //无参构造函数
        test(int n):value(n){} //有参...
        friend ostream& operator<<(ostream& output,test a); //重载插入运算符
        friend istream& operator>>(istream& input,test& a); //重载提取运算符
    
        test operator++() //前置运算符
        {
            this->value++;
            return *this;
        }
    
        test operator++(int) //后置运算符
        {
            test temp(*this);
            this->value++;
            return temp;
        }
    
    };
    
    ostream& operator<<(ostream& output,test a)
    {
        output<<a.value;
        return output;
    }
    
    istream& operator>>(istream& input,test& a)
    {
        cout<<"请输入对象的值value: ";
        input>>a.value;
        return input;
    }
    
    int main ()
    {
        test a;
        cin>>a;
        cout<<"++a "<<++a<<endl;
        cout<<"a++ "<<a++<<endl;
        cout<<"a   "<<a<<endl;
    
        return 0;
    }
    
    
    


  • 相关阅读:
    20170419数据结构
    20170418 random函数和range函数
    20170418 sum函数、
    20170417嵌套循环
    20170417循环(loop)
    linux 输入输出重定向
    cut 命令-截取文件中指定内容
    read 命令-从键盘读取变量的值
    xargs-命令
    find 在目录中查找文件
  • 原文地址:https://www.cnblogs.com/zhanyeye/p/9746116.html
Copyright © 2011-2022 走看看