当定义多个对象时,如何区分不同对象 eg:
#include<iostream>
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date n1;
n1.Init(2021, 6, 25);
Date n2;
n2.Init(2020, 5, 30);
}
n1调用Init时改变的是n1对象,n2调用Init时改变的是n2对象。是通过引入this指针解决该问题。
this指针的特性 1.this指针在类成员函数内部中使用。 2. this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参。 3. this指针是成员函数第一个隐含的指针形参,不需要手动传递。 4. this指针与形参一样存在栈中。 5. this指针是个关键字。不能用作变量名。 eg:
void Init(int year, int month, int day)
写出this指针为
void Init(Date*this,int year,int month,int day)
{
this->_year=year;
this->month=month;
....
}
int main()
{
Date n1;
n1.Init(&n1,2021,6,25);
}
eg:
#include<iostream>
class student
{
public:
void Init(int score)
{
_score = score;
}
void Print()
{
std::cout << "score" << std::endl;
}
private:
int _score;
};
int main()
{
student* s1 = nullptr;
s1->Init(75);报错
s1->Print();正常运行
}
s1是空指针s1->Init()this指针是NULL _score=score 可写为: this->_score=score 涉及空指针的访问,崩溃。
而s1->print()中没有涉及对空指针this的解引用正常运行且 print()函数的地址不在对象中保存,所以可以正常运行
|