01 成员变量和成员函数分开存储

02 this指针的使用

03 空指针调用成员函数

04 const修饰成员函数

 01 成员变量和成员函数分开存储

#include<iostream>
using namespace std;

//成员变量 和 成员函数 分开存储

class Person

{
    int m_a; //非静态成员变量 属于类的对象上

    static int m_b;  //静态成员变量 不属于类的对象上

    void m_c(){} //非静态成员函数 不属于类的对象上

    static void m_d() {} //静态成员函数 不属于类的对象上

};

void test1()

{

    Person p;

    //空对象内存空间为:1

    //c++编辑器给每个对象分配一个字节空间,是为了区分空对象占内存的位置

    //每个空对象也应该有一个独一无二的内存地址

    cout << "Person的内存空间大小" << sizeof(p) << endl;

}


void test2()

{

    Person p;

    cout << "Person的内存空间大小" << sizeof(p) << endl;

}

int main()

{

    //test1();

    test2();

    system("pause");

    return 0;
}

02 this指针的使用

#include<iostream>

using namespace std;



class Person

{

public:

    Person(int age)

    {
        //this指针指向 被调用的成员函数,所属的对象

        //不加this这三个age是同一个,相当于python的self.

        this->age = age;
    }



    //用引用方式返回一直返回p2

    Person& addage(Person& p)

    {

        this->age += p.age;

        return *this;

    }

    //值方式返回复制新的一份,返回新的对象

    Person addage2(Person& p)

    {

        this->age += p.age;

        //this指向p2指针,而*this指向的就是p2这个对象的本题

        return *this;

    }

    int age;

};



//1.解决名称冲突

void test1()

{

    Person p1(18);

    cout << "p1年龄为:" << p1.age << endl;

}

//2返回对象用*this,

void test2()

{

    Person p1(10);

    Person p2(20);

    //链式编程思想

    p2.addage(p1).addage(p1).addage(p1);

    cout << "带引用的,p2年龄为:" << p2.age << endl;

}



//3.引用改成值方式返回,

void test3()

{

    Person p1(10);

    Person p2(20);

    p2.addage2(p1).addage2(p1).addage2(p1);

    cout << "不带引用,值方式p2年龄为:" << p2.age << endl;


}

int main()

{

    //test1();

    test2();

    test3();

    system("pause");

    return 0;

}

03 空指针调用成员函数

#include<iostream>

using namespace std;



class Person

{

public:

    void showClassname()

    {

        cout << "这是class名字" << endl;

    }

    void showAge()

    {

        //保存原因传入空指针

        if (this == NULL)

        {

            return ;

        }

        cout << "年龄为" << this->age << endl;

    }

    int age;



};



void test1()

{

    Person * p1 = NULL;

    p1->showClassname();

    p1->showAge();



}



int main()

{

    test1();

    system("pause");

    return 0;

}

 04 const修饰成员函数

#include<iostream>
using namespace std;

class Person
{
public:
	//this指针的本质是指指针常量, 指针的指向是不可以修改的
	//const Person * const this;
	//成员函数后面加const,修饰是this指向,让指针指向的值也不可以修改

	void ctest1() const
	{
		//this->m_a = 100;
		//this = NULL; this指针不可修改指针的指向的
		this->m_b = 200;
	}
	void ctest2()
	{

	}
	int m_a;
	mutable int m_b;	//特殊变量,即使在常函数中,也可以修改这个值

};


void test1()
{
	Person p;
	p.ctest1();
	
}
//常对象
void test2()
{
	const Person p;	//在对象前加const,变为常对象
	//p.m_a = 100;
	p.m_b = 200; //m_b是特殊值,在常对象下也可以修改
	//常对象只能调用常函数
	p.ctest1();
	//p.ctest2(); //常对象不可以调用普通成员函数,因为普通成员函数可以修改属性

}

int main()
{


	system("pause");
	return 0;
}