您的位置:首页 > 编程语言 > C语言/C++

C++之全局函数与成员函数的转换

2017-10-10 14:38 260 查看
一、全局函数和成员函数

1、把全局函数转化成成员函数,通过this指针隐藏左操作数

Test add(Test &t1, Test &t2)===》Test add(Test &t2)

2、把成员函数转换成全局函数,多了一个参数

void 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指针回到元素状态

}

演示代码:
#include <stdio.h>

class Test1_1
{
public:
Test1_1 (int a)
{
this->a = a;
}

void print()
{
printf ("a = %d\n", a);
}

// 将全局函数改成内部函数可以通过 this 隐藏左操作数
int add(Test1_1 &b) //===> add(Test1_1 *const this, Test1_1 &b)
{
return this->a+b.GetA();
}

int GetA()
{
return a;
}
private:
int a;
};

int GetA(Test1_1 &obj)
{
return obj.GetA();
}

// 全局函数
int add(Test1_1 &a, Test1_1 &b)
{
return a.GetA()+b.GetA();
}

int main1_1()
{
Test1_1 a(10), b(20);

// int c = add(a, b);
int c = a.add(b); // a+b b.add(a) ===> b+a

printf ("c = %d\n",c);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: