this指针

本文探讨了在C++中通过修改输入参数来影响类成员变量的方法,包括参数名称修改、使用this指针等技巧,并通过实例展示了如何正确地在函数中对类成员进行赋值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream.h>
class point
{
public:
	int x;
	int y;
	point()
	{
		x=0;
		y=0;
	}
	point(int a,int b)
	{
		x=a;
		y=b;
	}
	void output()
	{
		cout<<x<<endl<<y<<endl;
	}
	void input(int x,int y)
	{

		x=x;
		y=y;
	}
};
void main()
{
	point pt(5,5);
	pt.input(10,10);
	pt.output();
}

       有人可能会认为在input(int x,int y)函数中,利用形参x和形参y对point类中的成员变量x和y进行了赋值,其实因为变量的可见性,point类的成员变量x和y在input(int x,int y)中是不可见的,所以实际上是将形参x的值赋给了形参x,形参y的值赋值给了形参y,没有给point类的成员变量x和y进行赋值,所以程序运行的结果是5,5.

       想在input(int x,int y)函数中对point类的成员变量x和y进行赋值:

(1)将input函数的参数名改为input(int a,int b)。

(2)利用this指针,

#include<iostream.h>
class point
{
public:
	int x;
	int y;
	point()
	{
		x=0;
		y=0;
	}
	point(int a,int b)
	{
		x=a;
		y=b;
	}
	void output()
	{
		cout<<x<<endl<<y<<endl;
	}
	void input(int x,int y)
	{

		this->x=x;
		this->y=y;
	}
};
void main()
{
	point pt(5,5);
	pt.input(10,10);
	pt.output();
}

运行结果为10,10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值