//全局函数和this指针函数 和函数返回元素,和函数返回引用的使用

//全局函数和this指针函数 和函数返回元素,和函数返回引用的使用 
#include<iostream>
using namespace std;
 class test
 {
     private:
     int a;
      int b; 
     public:
         test(int a=0,int b=0)
         {
             this->a =a; 
             this->b =b;
         }
         //t3=t1.testadd(t2); 
         test testadd(test &t2)
         {
             test tmp(this->a +t2.a ,this->b +t2.b );
             return tmp;
         }//t1.testadd2(t2) ;
         //返回一个引用,相当于返回自身  
         //返回t1这个元素,this就是&t1 
         test & testadd2( test &t2)//如果想返回对象本身,不能用函数重载 
         {
             this->a =this->a +t2.a ;
             this->b =this->b +t2.b ;
             return *this;  //吧*(&t1) 又回到了 t1元素 ,操作让this指针回到元素状态 
         }
         void print()
         {
             cout<<"a"<<a<<endl;
             cout<<"b"<<b<<endl;
         }
         ~test()
         {
             cout<<"析构函数"<<endl; 
          } 
      
 };
 
 //全局函数的方法 
 test testadd(test &t1,test &t2)//会产生一个匿名对象,关于匿名对象具体性质,以前的博客有提到 
 {
     test tmp;
     return tmp;
 }
 int main01()
 {
     test t1(1,2);
     test t2(3,4); 
     //思考,如何让t1+t2;
    test t3 ;
    //全局函数方法 
     t3=testadd(t1,t2);
     //成员函数方法 
     //先把测试案例写出来,降低自己写代码的难度
    //两种接匿名对象的方法: 
    test t4=t1.testadd(t2);//吧t1对象和t2对象相加,返回一个匿名对象,
    t4.print() ;                           //然后用这个匿名对象等号给t3;匿名对象直接转化成t4; 
    test t5;    
    t5=t1.testadd(t2);//匿名对象复制给t5; 
    t5.print() ;
     cout<<"hello"<<endl;
     return 0;
 }
//全局函数转成成员函数是少了一个参数。 
//成员函数转成全局函数是多了一个参数。
int main()
{
    test t1(1,2);
    test t2(3,4);
    //t1=t1+t2;
    t1.testadd2(t2) ; 
    t1.print(); 
   }   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值