C++_const修饰的是谁?

问题一:const修饰的是谁?

实验代码如下:

class Test
{
public:
	Test(int a, int b)
	{
		this->a = a;
		this->b = b;
	}
	void Var(int a,int b) const   //const修饰的this指针。,Var(const Test *this,int a,int b )
		{
		this->a = 100;
		this->b = 188;
		cout << a << endl;
	}
private:
	int a;
	int b;
};
int main()
{
	Test t1(20, 10);
	t1.Var(100, 200);
	system("pause");
	return 1;
}

说明:上面的 this->a = 100; this->b = 188; 是错误的,因为const修饰的this指针,再次修改这个值的时候就出现了错误。

全局函数PK成员函数

全局函数转换成员函数少了一个参数。
代码:

class Test
{
public:
	int a;
	int b;
public:
	Test TestAdd(Test &a1)
	{
		Test tmp(this->a + a1.a, this->b + a1.b);
		return tmp;
	}
public:
	Test(int a=0, int b=1)
	{
		this->a = a;
		this->b = b;
	}
public:
	void printT()
	{
		cout << a << b << endl;
	}
private:
};
//全局函数的方法。实现t1+t2;
Test TestAdd(Test &a1, Test &a2)
{
	Test tp;
	return tp;
}
void printT(Test *pT)
{
	cout << pT->a << endl;
}
int main()
{
	Test t1(1, 2);
	Test t2(2, 3);

	Test t3;
	t3 = TestAdd(t1, t2);  //调用全局函数。

	t3= t1.TestAdd(t2);
	t3.printT();
	system("pause");
	return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值