详解详解C++中的中的this指针与常对象指针与常对象
主要介绍了详解C++中的this指针与常对象,是C++入门学习中的基础知识,需要的朋友可以参考下
C++ this指针详解指针详解
this 是C++中的一个关键字,也是一个常量指针,指向当前对象(具体说是当前对象的首地址)。通过 this,可以访问当前对
象的成员变量和成员函数。
所谓当前对象,就是正在使用的对象,例如对于stu.say();,stu 就是当前对象,系统正在访问 stu 的成员函数 say()。
假设 this 指向 stu 对象,那么下面的语句中,this 就和 pStu 的值相同:
Student stu; //通过Student类来创建对象
Student *pStu = &stu;
[示例] 通过 this 来访问成员变量:
class Student{
private:
char *name;
int age;
float score;
public:
void setname(char *);
void setage(int);
void setscore(float);
};
void Student::setname(char *name){
this->name = name;
}
void Student::setage(int age){
this->age = age;
}
void Student::setscore(float score){
this->score = score;
}
本例中,函数参数和成员变量重名是没有问题的,因为通过 this 访问的是成员变量,而没有 this 的变量是函数内部的局部变
量。例如对于this->name = name;语句,赋值号左边是类的成员变量,右边是 setname 函数的局部变量,也就是参数。
下面是一个完整的例子:
#include <iostream>
using namespace std;
class Student{
private:
char *name;
int age;
float score;
public:
void setname(char *);
void setage(int);
void setscore(float);
void say();
};
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::say(){
cout<<this->name<<"的年龄是 "<<this->age<<",成绩是 "<<this->score<<endl;
}
int main(){
Student stu1;
stu1.setname("小明");
stu1.setage(15);
stu1.setscore(90.5f);
stu1.say();
Student stu2;
stu2.setname("李磊");
stu2.setage(16);
stu2.setscore(80);
stu2.say();