#include <iostream>
using namespace std;
class Test1
{
public:
Test1(int a=0,int b=0)
{
this->a=a;
this->b=b;
}
//成员函数
Test1& t_add(Test1 &t2)
{
this->a=this->a + t2.a;
this->b=this->b + t2.b;
return *this;
}
int a;
int b;
protected:
};
Test1 t_add(Test1 &t1,Test1 &t2)
{
Test1 t3;
t3.a=t1.a+t2.a;
t3.b=t1.b+t2.b;
return t3;
}
void main()
{
//从成员函数转化为全局函数 只需要加一个this 指针(指向本类的this指针)
//从全局函数转化为类的成员函数,需要减一个左操作数参数
Test1 t1(1,2),t2(3,4);
//Test1 t3=t_add(t1,t2);
t1.t_add(t2);
printf("%d %d\n",t1.a,t2.b );
system("pause");
}c++ 成员函数和全局函数的转换
最新推荐文章于 2025-09-08 02:30:00 发布
本文介绍了一个简单的 C++ 类 Test1 的定义及其实现,并演示了如何使用成员函数进行两个对象的数据相加操作。同时展示了如何将类成员函数转换为全局函数的方法。
2522

被折叠的 条评论
为什么被折叠?



