一、成员变量和成员函数分开存储
类的成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象
class Person
{
public:
int m_A;
float m_B;
char m_C;
double m_D; //内存对齐
};
Person p;
sizeof(p)=24
内存对齐:4 4 1+(3) 8 = 20
20+4=24 (24%8==0)
空对象占用内存空间:1
C++编译器会给每一个空对象分配一个字节的内存空间,区分空对象占用内存空间位置
二、this指针概念
类的每一个非静态成员函数指挥诞生一份函数实例
(多个同类的对象共同享有一份这块代码)
this 解决:这份共同享有的代码,是哪个对象调用的
this指针:指向被调用的成员函数所属的对象
this:隐含在 每一个非静态成员函数内 的指针
this 用途:1.形参和成员变量同名,用this 来区分
2.类的非静态成员函数中 返回对象本身 (return *this)
(1)Person& PersonAddAge(Person& p) //返回引用 //√
{
this->age += p.age;
return *this;
}//引用的方式,返回对象本身
(2) Person PersonAddAge(Person& p) //返回拷贝的新对象 //×
{
this->age += p.age;
return *this;
}//Person的方式,返回拷贝的新对象
Person p1(10);
Person p2(12);
//p2.PersonAddAge(p1) //返回对象p2
//(1)Person&,p2.age=42
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
//(2)Person, p2.age=22
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
拷贝方式返回新对象p',
拷贝方式返回新对象p'',
拷贝方式返回新对象p''',
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
//Person PersonAddAge(Person& p) //使用Person,返回拷贝的新对象
//{
// this->age += p.age;
// return *this; //返回拷贝的新对象
//}
Person& PersonAddAge(Person& p) //使用引用,返回对象本身
{
this->age += p.age;
return *this; //返回对象本身
}
public:
int age;
};
void test01()
{
Person p1(19);
cout << "p1的年龄:" << p1.age << endl;
}
void test02()
{
Person p1(10);
Person p2(12);
//p2.PersonAddAge(p1)->返回p2
p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); //链式编程思想
cout << "p2的年龄为:" << p2.age << endl;
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
三、空指针访问成员函数
类的空指针 访问 类的成员函数
Person* p1 = NULL;
void showAge()
{
if (this == NULL)
{
return;
}
//传入的指针为空,访问不了this->m_Age
cout << "age=" << this->m_Age << endl;
}
#include<iostream>
using namespace std;
class Person
{
public:
void showPerson()
{
cout << "this is Person" << endl;
}
void showAge()
{
if (this == NULL)
{
return;
}
//传入的指针为空,访问不了this->m_Age
cout << "age=" << this->m_Age << endl;
}
public:
int m_Age;
};
void test01()
{
Person* p1 = NULL;
//p1->showPerson();
p1->showAge();
}
int main()
{
test01();
system("pause");
return 0;
}
四、const修饰成员函数
1.常函数
常函数不可以修改成员属性
成员属性在声明时,加mutable后,在常函数中依然可以改变
2.常对象
常对象只能调用常函数
this的本质:指针常量(不可以修改指向)Person* const this;
成员变量加mutable,在 常函数 和 常对象 中都也可以修改它
class Person
{
public:
//Person* this
//Person* const this;
//const Person* const this; //常函数实质
void showPerson() const //加const ,this指针 指向的值也不可以修改
{
//this的本质:指针常量(不可以修改指向)
//this->m_A = 100; //错
//this = nullptr; //错
this->m_B = 100; //成员变量加mutable,在 常函数 和 常对象 中都也可以修改它
}
void func() { }
public:
int m_A;
mutable int m_B;
};
Person p1;
p1.showPerson(); //对,常对象只能调用常函数
p1.func(); //错