C++ 类和对象 this指针

先来一个C语言中的结构体

struct Student {
	char _name[20];
	char _gender[20];
	int _age;
};

在创建结构体变量后,要修改结构体中的变量的话,需要这样

int main()  {
Student s;
s->_name="balabala";
}

这样子来修改或者调用

比如说我要写一个函数初始化学生

void InitStudent(Student* this, char* name, char* gender, int age) {
	strcpy(this->_name, name);
	strcpy(this->_gender, gender);
	this->_age = age;
}

可以通过Student类型的指针来调用,那么C++中的类是如何实现调用的呢

class Stduent {
	void InitStudent(char* name, char* gender, int age) {
		cout << this << endl;
		strcpy(this->_name, name);
		strcpy(this->_gender, gender);
		this->_age = age;
	}
	void PrintStudent(Student* this) {
		cout << _name << ':' << _gender << ':' << _age << endl;
	}
	char _name[20];
	char _gender[20];
	int _age;
};
int main() {
	Stduent p1;
	//Student::InitStudent(&p1,"小鸡鸡", "男", 15) 对象地址传给this
	p1.InitStudent("小鸡鸡", "男", 15);
	return 0;
}

在整个学生类,发现在里面的成员函数中加上this以后也可以正常使用,这个this 就是C++为了实现封装而对用户透明的一个指针,这个隐藏的起来的指针会获取对象的地址,传给类中的成员函数,让用户实现想要实现的功能.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值