C++之全局函數和成員函數互相轉換


解析:成員函數會用this指針自動隱藏第一個操作數(左操作數)

1、把全局函數轉化成成員函數,通過this指針隱藏左操作數。

  Test add(Test &t1,Test &t2)     ==>    Test add(Test & t2);

2、把成員函數轉化成全局函數,多了一個參數

  vpid printAB()      ==>      void printAB(Test *pthis);

3、函數返回元素和返回引用

 Test &add(Test &t2)//*this //函數返回引用
  {
    this->a = this->a+t2.getA();
    this->b = this->b+t2.getB();
    return *this;//操作讓this指針回到元素狀態
  }
  Test add2(Test &t2)//*this //函數返回元素
  {
    //t3是局部變量
    Test t3(this->a+t2.getA(),this->b+t2.getB());
    return t3;
  }

 

函數返回元素,實例代碼:

#include<iostream>
using namespace std;

class Test
{
public:
	int a;
	int b;
public:
	~Test()
	{
		cout << "析構函數:" << "a:" << a << "b:" << b <<endl;
	}
	Test TestAdd(Test &t2)
	{
		Test tmp(this->a+t2.a,this->b+t2.b);
		return tmp;
	}
	Test(int a=0,int b=0)
	{
		this->a = a;
		this->b = b;
	}
	void printT()
	{
		cout << "a:" << a << "b:" << b <<endl;
	}
}

//把成員函數 轉成 全局函數 多了一個參數
void printT(Test *pt)
{
	cout << "a:" << pt->a << "b:" << pt->b <<endl;
}
//全局函數的方法
//全局函數 轉成 成員函數 少了一個參數
Test TestAdd(Test &t1,Test &t2)
{
	Test tmp;
	return tmp;
}

int main()
{
	Test t1(1,2);
	Test t2(3,4);
	
	Test t3;
	//全局函數方法
	t3 = t1.TestAdd(t2);
	
	//成員函數方法
	{
		Test t4 = t1.TestAdd(t2);//匿名對象直接轉化為t4
		t4.printT();
		Test t5;
		t5 = t1.TestAdd(t2);//匿名對象復制給t5
		t5.printT();
	}
	
	
	return 0;
}

  

函數返回引用,實例代碼:

#include<iostream>
using namespace std;

class Test
{
public:
	int a;
	int b;
public:
	~Test()
	{
		cout << "析構函數:" << "a:" << a << "b:" << b <<endl;
	}
         //t1.TestAdd(t2)
         //返回一個引用,相當於返回自身
         //返回t1這個元素,this就是&t1
	Test& TestAdd(Test &t2)
	{
		this->a=this->a+t2.a;
                this->b=this->b+t2.b;
		return *this;//*(&t1)又回到了t1元素
	}
	
	Test(int a=0,int b=0)
	{
		this->a = a;
		this->b = b;
	}
	void printT()
	{
		cout << "a:" << a << "b:" << b <<endl;
	}
}

//把成員函數 轉成 全局函數 多了一個參數
void printT(Test *pt)
{
	cout << "a:" << pt->a << "b:" << pt->b <<endl;
}
//全局函數的方法
//全局函數 轉成 成員函數 少了一個參數
Test TestAdd(Test &t1,Test &t2)
{
	Test tmp;
	return tmp;
}

int main()
{
	Test t1(1,2);
	Test t2(3,4);
	
         //t1=t1+t2;
	t1.TestAdd(t2);
        t1.printT();	
	
	return 0;
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM