第四课 类和对象-对象模型和this指针
4.3 C++对象模型和this指针
4.3.1 成员变量和成员函数分开储存
在C++中,类内的成员变量和成员函数分开存储
****只有非静态成员变量才属于类的对象上
class Person
{
int m_A; // 非静态成员变量
static int m_Number; // 静态成员变量
void m_func01() {}; // 静态成员函数
static void m_func02() {}; // 非静态成员变量
};
void test01()
{
Person p;
// 空对象占用内存空间为:1
// C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
// 每个空对象也应该又一个独一无二的内存地址
cout << "size of p = " << sizeof(p) << endl;
}
void test02()
{
Person p;
cout << "size of p = " << sizeof(p) << endl;
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
4.3.2 this指针概念
this指针指向被调用成员函数所属的对象
this是隐含每一个非静态成员函数内的一种指针
this指针的用途:
- 当形参和成员变量同名时,可用this指针来区分
class Person
{
public:
Person(int age)
{
this->age = age;
}
int age;
};
// 1.解决名称冲突
void test01()
{
Person p(23);
cout << "p的年龄:" << p.age << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
在类的非静态成员函数中,返回对象本身,可用 return *this
class Person
{
public:
Person(int age)
{
this->age = age;
}
Person & PersonAddAge(const Person p)
{
this->age += p.age;
// this指向p2的指针,而*this指向的就是p2这个对象的本体
return *this;
}
int age;
};
// 2.返回对象本身用*this
void test02()
{
Person p1(10);
Person p2(23);
// 链式编程思想
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout << "p2的年龄:" << p2.age << endl;
}
int main()
{
test02();
system("pause");
return 0;
}
4.3.3 空指针调用成员函数
空指针也可调用成员函数,但要注意有没有用到this指针,如果用到this指针,需要加以判断保证代码的健壮性
class Person
{
public:
void showClassName()
{
cout << "这是 Person 类" << endl;
}
void showPerson()
{
//
if (this == NULL)
{
cout << "this指针为NULL" << endl;
return;
}
// 报错原因是因为传入的指针是为NULL
cout << "age:" << this->m_Age << endl;
}
int m_Age;
};
void test01()
{
Person *p1 = NULL;
p1->showClassName();
p1->showPerson();
}
int main()
{
test01();
system("pause");
return 0;
}
4.3.4 const修饰成员函数
常函数:
- 成员函数后加const后我们称为该函数为常含数
- 常含数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数
class Person
{
public:
// this指针本质 是指针常量(指针的指向不可以修改,内容可以修改)
// Person * const this
// 在成员函数后加const,修饰的是this的指向,使指针指向的值也不可以修改
void func01() const
{
//this->m_A = 10;
this->m_B = 25;
}
void func02()
{
}
int m_A;
mutable int m_B; // 特殊变量,即在常函数中,也可以修改这个值,加关键字mutable
};
int main()
{
const Person p1; // 对象前加const 变为常对象
//p1.m_A = 10; // 不能修改
p1.m_B = 10; // 可以修改
p1.func01(); // 常对象只能调用常函数
system("pause");
return 0;

浙公网安备 33010602011771号