//this 指针概念
//this 指针指向被调用的成员函数所属对象
/*class person
{
public:
person(int age)
{
m_age = age;
}
int m_age;//m_表示成员member
};*/
class person
{
public:
person(int age)
{
this->age = age;this 指针指向被调用的成员函数所属对象
}
int age;
person& personaddage(person& p)//返回本体要用引用的方式返回//用值返回会返回不同于p2的东西
{
this->age += p.age;
//this指向p2的指针,而*this指向p2这个对象的本体
return *this;
}
};
// 1.解决名称冲突
//
void test01()
{
person p1(18);
cout << "p1年龄" << p1.age << endl;
}
// 2.返回对象本身用*this
void test02()
{
person p1(10);
person p2(10);
//链式编程思想
p2.personaddage(p1).personaddage(p1).personaddage(p1);
cout << "p2年龄" << p2.age << endl;
}
int main()
{
test01();
test02();
空指针访问成员函数
C++中的空指针也可以调用成员函数的,但是要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
//空指针调用成员函数
class person
{
public:
void showclassname()
{
cout << "this is Person class" << endl;
}
void showpersonage()
{
//报错的原因是因为传入的指针是为NULL
if (this == NULL)
{
return;
}//这几行判断是为了保证代码的健壮性
cout << "age=" << this->m_age << endl;
}
int m_age;
};
void test01()
{
person* p = NULL;//空
p->showclassname();
p->showpersonage();//调用后面的函数
}
int main()
{
test01();
const修饰成员函数
//const修饰成员函数
//常函数 成员函数后加const后我们称这个函数为常函数
// 常函数内不可以修改成员属性
// 成员属性声明时加关键字mutable后,在常函数中仍然可以修改
class person
{
public:
//this指针的本质:指针常量 指针的指向是不可以修改的
//这个案例里面的this 相当于 person *const this; 要使指针指向的值都不可以改 要写为const person *const this;
//然后后面加const就相当于指针指向,指针指向值也不可以改。所以在成员函数后面加const,修饰的是this指针
void showperson() const
{
this->m_b = 100;
//隐含在每个成员函数内部都有一个指针
//m_a;//this->m_a=100;//m_a = 100;常函数内不可以修改成员属性 都错
//this = NULL;也错,因为下面的测试案例,this已经指向p了,不可以再指向别的地方
}
void func()
{
}
int m_a;
mutable int m_b;//特殊变量,即使在常函数中,也可以修改这个值,加上关键字mutable
};
void test01()
{
person p;
p.showperson();
}
//常对象
//声明对象前加const称该对象为常对象
//常对象只能调用常函数
void test02()
{
const person p;//在对象前加const,变为常对象
//p.m_a = 100;错,同上面一样,不可修改
p.m_b = 100;//m_b是特殊值,在常对象下也可修改
//常对象只能调用常函数
p.showperson();
//p.func();错,因为普通函数是可以修改m_a的,但是常对象本身是不允许修改属性的,矛盾了
//常对象 不可以调用普通成员函数,因为普通成员函数可以修改属性
}
int main()
{
test01();
test02();
system("pause");
return 0;
}