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

    #include<iostream.h> //注意这里使用带h的头文件,不然在vc里编译通不过
                         //再次强调下,只要是在class member中有 pointer的存在,class 就应该提供 copy constructor 和 operator =.
    
    class A
    {
    public:
        A():data(0){};
        A(A &b)
        {
            cout << "copy constructor" << endl;
            data = b.data + 2;
        }
        A(int _data):data(_data){};
    
        A& operator = (A &a)
        {
            cout << "= operator" << endl;
            data = a.data+1;
            return *this;
        }   
    

          A& operator += (const A &a)
         {
              data += a.data;
              return (*this);
          }

    void show(A &a)  //一开始,脑子秀逗啦,以为a.data会发生编译错误,                     
        {                //连下面的友元函数都可以这样用,自己的成员函数为什么不行呢?
            cout << a.data << endl;
        }
        friend void show2(A &a);
        friend A operator + (const A &a, const A &b);
        friend ostream& operator << (ostream &out, A &a);
    
    private:
        int data;
    };
    
    
    void show2(A &a)
    {
        cout << a.data << endl;
    }
    
    A operator + (const A &a, const A &b)
    {
        A temp;
        temp.data = a.data + b.data;
        return temp;
    }
    
    ostream& operator << (ostream &aout, A &a)
    {
        aout << "I am " << a.data << endl;
        return aout;
    }
    
    
    
    int main(void)
    {
        A a(3);
        A b1=a; //注意,这里调用的是copy构造函数,与A b1(a)是一样的
        A c;
        c = a; //这里,调用的是operator =
    
        show2(a);
        b1.show(b1);
        c.show(c);
    
        cout << a;
    
        A d;
        d = a+a;
        show2(d);
    
    A f1(2);
    A f2(2);
    f1 += f2;
    show2(f1);
    return 0; }

    输出

    copy constructor
    = operator
    3
    5
    4
    I am 3
    copy constructor
    = operator
    9
    4

       (1)最后为什么是9呢,因为在operator +函数里,temp中的data为6,operator +函数结束时,将temp复制给main函数里面的一个临时变量(姑且叫做main_temp),即调用copy构造函数,然后执行operator = 函数,完成d=main_temp的赋值

    (2)为什么operator +的返回值不能是引用类型呢,像下面这样
    friend A& operator + (const A &a, const A &b);
    因为temp的作用域就在operator里面,当该函数结束的时候,temp也就结束啦,这时把一个生命已经结束的变量的地址返回到主函数,这不是笑话吗
    (3)
    ostream& operator << (ostream &aout, A &a)那这里面的返回值怎么是引用类型啊,因为传递来的参数就是引用类型啊

    int main(void)
    {
        A a(3);
        A d1 = a+a;
        d1.show();  //10
    
        A d2;
        d2 = a+a;
        d2.show(); //9
    
        return 0;
    }
  • 相关阅读:
    oracle,mysql对敏感,关键字等处理
    eclipse内置tomcat启动方法
    plsql登录弹白框
    date
    linux乱码
    环境变量
    终端类型
    netstat -aon|findstr 8888 终止进程
    export
    bash环境变量读取顺序
  • 原文地址:https://www.cnblogs.com/zzj2/p/3011068.html
Copyright © 2011-2022 走看看