this指针永远指向当前对象
成员函数通过this指针即可知道操作的是那个对象的数据。This指针是一种隐含指针,它隐含于每个类的非静态成员函数中。This指针无需定义,直接使用即可。
注意:静态成员函数内部没有this指针,静态成员函数不能操作非静态成员变量。
this指针的使用
当形参和成员变量同名时,可用this指针来区分
在类的非静态成员函数中返回对象本身,可使用return *this
// 38.this.cpp : 定义控制台应用程序的入口点。
//
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
// this可以解决命名冲突
class Person
{
public:
Person(int age)
{
this->age = age;
}
//对比年龄
void compareAge(Person & p)
{
if (this->age == p.age)
{
cout << "年龄相等" << endl;;
}
else
{
cout << "年龄不相等" << endl;;
}
}
//年龄相加
Person& PlusAge(Person & p)
{
this->age += p.age;
return *this; //*this指向对象本体
}
int age;
};
void test01()
{
Person p1(10);
cout << "p1的年龄" << p1.age << endl;//p1的年龄10
Person p2(10);
p1.compareAge(p2);
p1.PlusAge(p2).PlusAge(p2).PlusAge(p2); //链式编程
cout << "p1的年龄" << p1.age << endl;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
输出
p1的年龄10
年龄相等
p1的年龄40
空指针访问成员函数
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
void show()
{
cout << "Person show" << endl;
}
void showAge()
{
if (this == NULL)//防止空指针异常
{
return;
}
cout << this->m_Age << endl; // NULL -> m_Age
}
int m_Age; //
};
void test01()
{
Person * p = NULL;
p->show();//Person show
p->showAge();//
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
const修饰成员函数
用const修饰的成员函数时,const修饰this指针指向的内存区域,成员函数体内不可以修改本类中的任何普通成员变量。
当成员变量类型符前用mutable修饰时例外
常函数 void func() const {} 常函数
常函数 修饰是this指针 const Type * const this
常函数 不能修改this指针执行的值
常对象 在对象前 加入 const修饰 const Person p1
常对象 不可以调用普通的成员函数
常对象 可以调用常函数
用mutable修饰的关键字是在常函数可以修改的
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
//构造中修改属性
//this 永远执行本体
this->m_A = 0;
this->m_B = 0;
}
void showInfo() const //常函数 不允许修改指针指向的值
{
//this->m_A = 1000;
this->m_B = 1000;
// const Person * const this
cout << "m_A = " << this->m_A << endl;//m_A = 0
cout << "m_B = " << this->m_B << endl;//m_B = 1000
}
void show2() const
{
//m_A = 100;
}
int m_A;
mutable int m_B; //就算是常函数 我还是执意要修改
};
void test01()
{
Person p1;
p1.showInfo();
//常对象 不允许修改属性
const Person p2;
cout << "p2.m_A = " << p2.m_A << endl;//p2.m_A = 0
p2.show2();
//常对象 不可以调用普通成员函数
//常对象 可以调用常函数
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}