this指针
每个成员函数都有一个隐含的参数:当前类的指针
指向调用函数的对象
函数中涉及的成员都是this指针指向的对象的成员\
const Stock &Stock::topVal(const Stock &a) const
{
if (a.total_val) > total_tal
return a;
else return *this;
}
this 只能用在类的内部,通过 this 可以访问类的所有成员,包括 private、protected、public 属性的\
this 到底是什么
this 实际上是成员函数的一个形参,在调用成员函数时将对象的地址作为实参传递给 this。不过 this 这个形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默地将它添加到参数列表中。
#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;
}