前言:
自己在程序的时候一般不用this,但是在后来发现越来越有必要好好整理一下该知识点了,如有不足之处以及缺漏之处还望各位读者指出。
概念&实例
this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。所谓当前对象,是指正在使用的对象。this 只能用在类的内部,通过 this 可以访问类的所有成员,包括 private、protected、public 属性的。
#include <iostream>
using namespace std;
class Student{
public:
void setname(char *name);
void setage(int age);
void setscore(float score);
void show();
private:
char *name;
int age;
float score;
};
void Student::setname(char *name){
this->name = name;
}
void Student::setage(int age){
this->age = age;
}
void Student::setscore(float score){
this->score = score;
}
void Student::show(){
cout<<this->name<<"的年龄是"<<this->age<<",成绩是"<<this->score<<endl;
}
int main(){
Student *pstu = new Student;
pstu -> setname("李华");
pstu -> setage(16);
pstu -> setscore(96.5);
pstu -> show();
return 0;
}
本例中成员函数的参数和成员变量重名,只能通过 this 区分。以成员函数setname(char *name)
为例,它的形参是name
,和成员变量name
重名,如果写作name = name;
这样的语句,就是给形参name
赋值,而不是给成员变量name
赋值。而写作this -> name = name;
后,=
左边的name
就是成员变量,右边的name
就是形参,一目了然。需要注意的是:this 是一个指针,要用->
来访问成员变量或成员函数。
原文链接: https://www.cnblogs.com/shierlou-123/p/12376117.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/193699
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!