1. 成员变量和成员函数分开存储
- 在C++中,类内的成员变量和成员函数分开存储,只有非静态成员变量才属于类的对象上
- 空对象占用内存空间为:1 ————> C++编译器会给每个空对象也分配一个字节空间,为了区分对象占用内存的位置,也就是说每个空对象应该有一个独一无二的内存地址
#include <iostream>
using namespace std;
//成员变量和成员函数分开存储
class Person
{
public:
int m_a;//非静态成员变量,属于类的对象上
static int m_b;//静态成员函数,不属于类对象
void func(){}//非静态成员函数,不属于类的对象上
void func2(){}//静态成员函数,不属于类的对象上
};
void test01() //当类中为空时
{
Person p;
//空对象占用内存空间为:1
//原因:C++编译器会给每个空对象也分配一个字节空间,为了区分对象占用内存的位置,也就是说每个空对象应该有一个独一无二的内存地址
cout << "size of p:"<< sizeof(p) << endl;
}
void test02() //当类中为非空时
{
Person p;
//空对象占用内存空间为:4
cout << "size of p:"<< sizeof(p) << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
2. this 指针
C++ 通过this 指针来解决非静态成员函数只有一份函数,且在被多个类型相同的对象调用时无法区分的问题 ————> 静态成员函数只能访问静态成员变量,不能访问非静态成员函数变量(无法区分到底是哪个对象上的数据)
this 指针作用
- this 指针指向被调用的成员函数所属的对象
- this 指针是隐含每一个非静态成员函数内的一种指针
- this 指针不需要定义,直接使用。
this 指针的用途 - 当形参和成员变量同名时,可用this指针来区分
- 在类的非静态成员函数中返回对象本身,可以使用return *this
注:在以值方式返回局部对象时会调用拷贝构造函数
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)//形参与成员变量同名
{
this -> age = age; //this 指针指向被调用的成员函数所属的对象
}
Person& Personaddage(Person &p) //用引用的方式返回,一直返回test02中的p2;如果用值返回,每次返回都是一个新的对象
{
this -> age+=p.age;
return *this; //this 是指向所调用对象本身
}
int age;
};
//1. 解决名称冲突
void test01()
{
Person p1(18);
cout << "p1的年龄" << p1.age << endl;
}
// 2. 返回对象本身用 *this
void test02()
{
Person p1(10);
Person p2(10);
//链式编程思想
//用引用返回为40,值返回为20;由于值传递返回会调用拷贝构造函数,故每次返回都是一个新的对象
p2.Personaddage(p1).Personaddage(p1).Personaddage(p1);
cout << "p2的年龄为:" << p2.age << endl; //由于输出的是 p2 的年龄,所以值返回为20。
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
3. 空指针访问成员函数
C++ 中空指针也是可以调用成员函数的,但是要注意有没有用到this指针,如果用到this 指针,需要加以判断保证代码的健壮性
#include <iostream>
using namespace std;
//空指针调用成员含数
class Person
{
public:
void showclassname()
{
cout << "this is Person class" <<endl;
}
void showpersonage()
{
if (this == NULL)
{
return;
}
cout << "age=" << this->m_age <<endl;//如果没有上面 if 语句会报错,报错原因:是因为传入的指针是NULL
}
int m_age;
};
void test01()
{
Person *p =NULL;
p -> showclassname();
p -> showpersonage();
}