• C++基本之 运算符重载


    =====>友元运算符
    #include <iostream> using namespace std; class Test { public: Test(int a = 0) { Test::a = a; } friend Test operator +(Test&,Test&); friend Test& operator ++(Test&,int); public: int a; }; Test operator +(Test& temp1,Test& temp2)//+运算符重载函数 { //cout<<temp1.a<<"|"<<temp2.a<<endl;//在这里可以观察传递过来的引用对象的成员分量 Test result(temp1.a+temp2.a); return result; } Test& operator ++(Test& temp,int)//++运算符重载函数 { temp.a++; return temp; } int main() { Test a(100); Test c=a+a; cout<<c.a<<endl; c++; //这样可以c++ cout<<c.a<<endl; // system("pause"); }
    friend Test& operator ++(Test&);
    
    Test& operator ++(Test& temp)//++运算符重载函数
    {
        temp.a++;
        return temp;
    }
    
    这样的话,必须是++c

     ===>类成员运算符:

    #include <iostream>
    using namespace std;
    
    class Test
    {
        public:
            Test(int a = 0)
            {
                Test::a = a;
            }
            Test(Test &temp)
            //运算符重载函数为值返回的时候会产生临时变量,临时变量与局部变量result的复制会调用拷贝构造函数,临时变量的生命周期是在拷贝构造函数运行完成后才结束,但如果运算符重载函数返回的是引用,那么不会产生临时变量,而局部变量result的生命周期在运算符重载函数退出后立即消失,它的生命周期要比临时变量短,所以当外部对象获取返回值的内存地址所存储的值的时候,获得是一个已经失去效果的内存地址中的值,在这里的值返回与引用返回的对比,证明了临时变量的生命周期比局部变量的生命周期稍长。
            {
                cout<<"载入拷贝构造函数"<<"|"<<temp.a<<endl;//注意这里,如果修改运算符重载函数为返回引用,这里就会出现异常,temp.a将获得一个随机值。
                Test::a = temp.a;
            }
            ~Test()//在mian()内析构的过程是result局部变量产生的
            {
                cout<<"载入析构函数!"<<endl;
                cin.get();
            }
            Test operator +(Test& temp2)//+运算符重载函数
            {
                //cout<<this->a<<endl;
                Test result(this->a+temp2.a);
                return result;
            }
            Test& operator ++(int)  //后置运算符
            {
                this->a++;
                return *this;
            }
            Test& operator ++()//++运算符重载函数  前置运算符
    
            //递增运算符是单目运算符,使用返回引用的运算符重载函数道理就在于它需要改变自身。
            //在前面我们学习引用的单元中我们知道,返回引用的函数是可以作为左值参与运算的,这一点也符合单目运算符的特点。
            //如果把该函数改成返回值,而不是返回引用的话就破坏了单目预算改变自身的特点,程序中的++(++c)运算结束后输出c.a,会发现对象c只做了一次递增运算,原因在于,当函数是值返回状态的时候括号内的++c返回的不是c本身而是临时变量,用临时变量参与括号外的++运算,当然c的值也就只改变了一次。
            {
                this->a++;
                return *this;
            }
        public:
            int a;
    };
    
    int main()
    {
        Test a(100);
        Test c;
        c=a+a;
        cout<<c.a<<endl;
        c++;
        cout<<c.a<<endl;
        ++c;
        cout<<c.a<<endl;
        ++(++c);
        cout<<c.a<<endl;
        //system("pause");
    }

    补充:http://www.cppblog.com/kangnixi/archive/2010/02/17/107972.html#userconsent#

  • 相关阅读:
    第十五章:Android 调用WebService(.net平台)
    第十四章:样式(Style)和主题(Theme)
    第十三章:常用控件下
    第十三章:常用控件上
    第十二章:Android数据存储(下)
    第十一章:Android数据存储(上)
    第十章:Intent详解
    PHP7.X连接SQLSERVER数据库(CENTOS7)
    CentOs install oracle instant client
    softmax
  • 原文地址:https://www.cnblogs.com/qbmiller/p/3812312.html
Copyright © 2020-2023  润新知