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;
}
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;
}
相关文章推荐
- c++ 成员函数和全局函数的转换
- C++之全局函数和成员函数的转换
- C++如何在类的成员函数中表示同名的全局变量?
- C++ 静态数据成员 成员函数 静态变量 全局变量(1)
- C++的 成员函数指针, 静态函数指针,全局函数指针 区别
- C++ Hook(钩子)编程,通过内联汇编,使类成员函数代替全局函数(静态函数)
- C++中使用非静态成员函数代替全局函数
- C++全局函数与成员函数的区别
- [C++]static全局变量/全局变量,static函数/普通函数,函数中static变量/函数中的变量,类中的static成员变量/普通类成员变量
- 隐式类型转换与非成员函数(effective C++ 条款24&46)
- C++中Operator类型强制转换成员函数解析
- c++中静态成员变量 静态成员函数 全局变量与静态函数的关系 字符串中括号的匹配编程 (笔试经历)
- c++ 如何把this指针传入成员函数 像全局函数一样调用成员函数
- C++成员函数强制转换,适应C风格!
- C++调用全局函数与类成员函数
- C++中Operator类型强制转换成员函数
- C++ static CString 变量在成员函数与全局函数中的不同表现
- c++ 成员函数 普通函数指针转换
- c++ 全局函数指针和类成员函数指针
- c++ 父类指针转换为子类指针后调用子类的成员函数问题