C++ 全局函数与成员函数(返回元素 引用 *this)

#include<iostream>
using namespace std;

class test
{
public:
	int a;
	int b;
public:
	test(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
		cout << "a=" << a << ",b=" << b ;
		cout << "I am test()"<< endl;
	}
	~test()
	{
		cout << "a=" << a << ",b=" << b;
		cout << "I am ~test()"<< endl;
	}
	//成员函数 返回的是一个元素
	test Add(test &obj)
	{
		test t(this->a + obj.a, this->b + obj.b);
		return t;
	}
	//返回的是一个引用  并且用*this返回
	//返回一个引用 相当于返回自身
	//返回t1这个元素 this就是t1
	test& Add1(test& obj1)
	{
		this->a = this->a + obj1.a;
		this->b = this->b + obj1.b;
		return *this;//把*(&t1)又回到了t1自身
	}
	void printfA()
	{
		cout << "a="<<a<<",b="<<b<< endl;
	}

};
//成员函数转成全局函数 多了一个参数
void printfB(test *pt)
{
	cout << "a:"<<pt->a<<"b:"<<pt->b<< endl;
}
//全局函数
//全局函数转成成员函数 少了一个参数
test Addt(test &t1, test& t2)
{
	test t;
	return t;
}
void main()
{
	test t1(1, 2);
	test t2(3, 4);
	test t3 = Addt(t1, t2);//调用全局函数
	printfB(&t3);  
	test t4 = t1.Add(t2);
	test t5;
	t5 = t1.Add(t2);
	t4.printfA();

	t1.Add1(t2);
	t1.printfA();
	system("pause");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值