先来一个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++为了实现封装而对用户透明的一个指针,这个隐藏的起来的指针会获取对象的地址,传给类中的成员函数,让用户实现想要实现的功能.