4.3.1 成员变量和成员函数分开存储
在c++中,类内的成员变量和成员函数分开存储,只有非静态成员变量才属于类的对象上
#include <iostream>
using namespace std;
class Person
{
int m; //非静态成员变量 属于类的对象上
static int a; //静态成员变量 不属于类对象上
void func() {} //非静态成员函数 不属于类对象上
static void func2(){} //静态成员函数 不属于类的对象上
};
void test01()
{
Person p;
//空对象占用内存空间为:1
//C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
//每个空对象也应该有一个独一无二的内存地址
cout << "size of p = " << sizeof(p) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
4.3.2 this 指针
this指针指向被调用成员函数所属对象
this指针的用途:
1、当形参和成员变量同名时,可用this指针来区分
2、在类的非静态成员函数中返回对象本身,可使用return *this
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
// this指针指向 被调用成员函数 所属对象
//p1调用该成员函数,this指针指向p1
this->age = age;
}
//Person PersonAddAge(Person &p)
//如果用 值 引用,每次会创建一个新的对象,p2调用该函数,会创建一个p2'新对象
Person& PersonAddAge(Person &p)
{
this->age += p.age;
// this 指针指向p2的指针,而*this指向的就是p2这个对象的本体
return *this;
}
int age;
};
//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();
system("pause");
return 0;
}
4.3.3 空指针访问成员函数
C++中空指针也是可以调用成员函数的,但是要注意有没有用到this指针,如果用到this指针,需要加以判断保证代码的健壮性
#include <iostream>
using namespace std;
class Person
{
public:
void ShowPersonName()
{
cout << "this class Person" << endl;
}
void ShowPersonAge()
{
if (this == NULL)
{
return;
}
cout << "age = " << this->m_Age << endl;
}
int m_Age;
};
//空指针可以访问成员函数
void test01()
{
Person *p = NULL;
p->ShowPersonName();
p->ShowPersonAge();
}
int main()
{
test01();
system("pause");
return 0;
}
4.3.4 const 修饰成员函数
常函数:
1、成员函数后加const,称这个函数为常函数
2、常函数内不可以修改成员属性
3、成员属性声明时加关键字 mutable后,在常函数中依然可以修改
常对象:
1、声明对象前加const称改对象为常对象
2.常对象只能调用常函数
#include <iostream>
using namespace std;
class Person
{
public:
//this指针的本质 是指针常量 指针的指向是不可以修改的
//const Person * const this;
//在成员函数后加const,修饰的是this的指向,让指针指向的值也不可以修改
void ShowPerson() const
{
//this->m_Age = 100; //this 指针指向不可以修改
this->m_B = 100;
//this = NULL;
}
void func();
int m_Age;
mutable int m_B;//特殊变量,在常函数中依然可以修改
};
//常函数
void test01()
{
Person p;
p.ShowPerson();
}
//常对象
void test02()
{
const Person p2;//对象前边加const 变为常对象
//p2.m_Age = 100; 普通变量常对象也不可以修改
p2.m_B = 10; //m_B是特殊值,在常对象下可以修改
//常对象只能调用常函数
p2.ShowPerson();
//p2.func(); //常对象不可以调用普通函数,普通成员函数可以修改属性
}
int main()
{
test01();
system("pause");
return 0;
}