当前位置:编程学习 > C/C++ >>

C++运算符+,+=,<<,=重载范列

单操作符用返回引用,不能是友元函数,否则编译不通过

双操作符,必须定义为友元,否则编译不通过

测试编译器:g++ 4.6.3

 

 


[cpp]
#include <iostream>  
#include <ostream>  
#include <string>  
using namespace std; 
class T{ 
    public: 
        T(){}; 
        T(int t) 
        { 
            a = t; 
        }; 
        T(const T &t)//当没有定义复制函数,编译器会自己合成一个,并不会调用下面的赋值”=“操作符。  
        { 
            cout << "复制" << endl; 
            a = t.a; 
        }; 
        T& operator = (const T& t)//当没有定义赋值函数,编译器会自己合成一个,并不会调用下面的复制”()“操作符。  
        { 
            cout << "赋值" << endl; 
            a = t.a; 
            return *this; 
        } 
        T& operator += (int b) 
        { 
            a += b; 
            return *this; 
        } 
     
 
    private://友元函数可以为私有类,因为友元不是类成员,所以私有限制对他不起作用  
        friend  ostream& operator << (ostream& out,const T& t)//必须设为友元函数,否则编译不通过  
        { 
            out << "the num is:" << t.a; 
            return out; 
        } 
     
        friend  T operator + (const T& t1, const T& t2)//必须设为友元函数,否则编译不通过  
        { 
            T t; 
            t.a = t1.a + t2.a; 
            return t; 
        } 
        int a; 
}; 
void fun(T t) 

    return ; 

int main() 

    T t(2); 
    fun(t);//形参传递为复制函数  
    T t1; 
    t1 = t;//赋值操作符号  
    t1 += 5; 
    cout << t1 << endl; 
    T t2;// 如果是t2 = t + t1;初始化为复制函数,等价与t2(t + t1)  
    t2 = t + t1;//先加,在调用=  
    cout << t2 << endl; 
    return 0; 

#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class T{
 public:
  T(){};
  T(int t)
  {
   a = t;
  };
  T(const T &t)//当没有定义复制函数,编译器会自己合成一个,并不会调用下面的赋值”=“操作符。
  {
   cout << "复制" << endl;
   a = t.a;
  };
  T& operator = (const T& t)//当没有定义赋值函数,编译器会自己合成一个,并不会调用下面的复制”()“操作符。
  {
   cout << "赋值" << endl;
   a = t.a;
   return *this;
  }
  T& operator += (int b)
  {
   a += b;
   return *this;
  }
 

 private://友元函数可以为私有类,因为友元不是类成员,所以私有限制对他不起作用
  friend ostream& operator << (ostream& out,const T& t)//必须设为友元函数,否则编译不通过
  {
   out << "the num is:" << t.a;
   return out;
  }
 
  friend T operator + (const T& t1, const T& t2)//必须设为友元函数,否则编译不通过
  {
   T t;
   t.a = t1.a + t2.a;
   return t;
  }
  int a;
};
void fun(T t)
{
 return ;
}
int main()
{
 T t(2);
 fun(t);//形参传递为复制函数
 T t1;
 t1 = t;//赋值操作符号
 t1 += 5;
 cout << t1 << endl;
 T t2;// 如果是t2 = t + t1;初始化为复制函数,等价与t2(t + t1)
 t2 = t + t1;//先加,在调用=
 cout << t2 << endl;
 return 0;
}

 

 

输出结果为:

复制
赋值
the num is:7
赋值
the num is:9

 

 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,