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;
}

  

原文地址:https://www.cnblogs.com/cthon/p/9180266.html