this指针的用途
#include<iostream>
using namespace std;
//解决名称冲突
//返回对象本身 *this
class Person {
public:
int age;
Person(int age) {
//this指针指向的是被调用的成员函数所属的对象
this->age = age;
}
Person & personAddage(Person &p) {
this->age += p.age;
return *this;
}
};
void test01() {
Person p1(18);
cout << "p1的年龄为:" << p1.age << endl;
}
void test02() {
Person p1(10);
Person p2(10);
//链式编程思想
p2.personAddage(p1).personAddage(p1).personAddage(p1);
cout << "p2的年龄为:" << p2.age << endl;
}
int main() {
//test01();
test02();
}
空指针访问成员函数
#include<iostream>
using namespace std;
//空指针可以调用成员函数
class Person {
public:
void showClassName() {
cout << "this is Person class" << endl;
}
void showPersonAge() {
if (this == NULL)//提高健壮性,为NULL直接返回
return;
cout << "age = " << m_age << endl;
}
int m_age;
};
void test01() {
Person* p = NULL;
p->showClassName();
//p->showPersonAge();//报错原因传入指针为NULL
}
int main() {
test01();
return 0;
}
const修饰成员函数
#include<iostream>
using namespace std;
//常函数,常对象
class Person {
public:
//this指针的本质是指针常量 指针指向的是不可以修改的
//const Person * const this
//在成员函数后面加const,修饰的是this指向,让指针指向的值也不能修改
void showPerson() const
{
m_b = 100;
//m_a = 100;
//this = NULL//this指针不可以修改指针的指向
}
void fun() {
}
int m_a;
mutable int m_b;//特殊变量 即使在常函数中 也可以修改 必须加mutable
};
void test01() {
Person p;
p.showPerson();
}
void test02() {
const Person p;//在对象前加const,变为常对象
//p.m_a = 100;
p.m_b = 100;//因为加了mutable,所以可以修改
p.showPerson();//常对象只能调用常函数
//p.fun()//常对象不能调用普通成员函数,普通成员函数可以修改成员变量
}
int main() {
test02();
return 0;
}
全局函数做友元
#include<iostream>
using namespace std;
class Building {
//goodGay全局函数是Building的友元,可以访问私有成员
friend void goodGay(Building* building);
public:
Building() {
m_SittingRom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRom;
private:
string m_BedRoom;
};
void goodGay(Building *building) {
cout << "好基友的全局函数 正在访问" << building->m_SittingRom << endl;
cout << "好基友的全局函数 正在访问" << building->m_BedRoom << endl;
}
void test01() {
Building building;
goodGay(&building);
}
int main() {
test01();
}
类做友元
#include<iostream>
using namespace std;
class Building;
class GoodGay {
public:
GoodGay();
void visit();//参观函数访问building中的属性
Building* building;
};
class Building {
//GoodGay是本类的友元,可以访问私有成员
friend class GoodGay;
public:
Building();
string m_SittingRoom;
private:
string m_BedRoom;
};
//类外写成员函数
Building::Building() {
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay() {
building = new Building;
}
void GoodGay::visit() {
cout << "好基友正在访问" << building->m_SittingRoom << endl;
cout << "好基友正在访问" << building->m_BedRoom << endl;
}
void test01() {
GoodGay gg;
gg.visit();
}
int main() {
test01();
return 0;
}