C++----类的成员变量和成员函数在类的储存方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XUCHEN1230/article/details/84973365

类的成员变量和成员函数在类的储存方式为分开存储。

即只有非静态变量储存在类中,其余的所有成员均不在类中。

实验如下:

exp1:

class Person1
{



};


void test01()
{

	cout << "size of (空类Person)是:" << sizeof(Person1) << endl;
}

//空类的大小是1,每个实例的对象,都有独一无二的地址。
//每个地址,都有第一无二的char 来维护这个地址。
//这就是空类的大小;

exp2:

class Person2
{
public:
	int m_Age;
};

void test02()
{
	cout << "size of Person2 是:" << sizeof(Person2) << endl;
}

//运行结果为 4 ;
//m_Age 属于非静态的成员变量,属于对象身上;

exp3:

class Person3
{
public:
	int m_Age;
	void func(){}

};

void test03()
{
	cout << "size of Person3 是:" << sizeof(Person3) << endl;
}

//结果还是4;

//成员属性和成员函数是分开存储的;
//非静态的成员函数不属于对象身上;

exp4:

class Person4
{
public:
	int m_Age;
	void func() {};
	static int m_B;

};

void test04()
{
	cout << "size of Person4 是:" << sizeof(Person4) << endl;
}

//结果还是4;
//说明静态的变量为共享数据,不是对象(类)身上的东西
 

exp5:

class Person5
{
public:
	int m_Age;
	void func() {};
	static int m_B;
	static void func2() {};

};

void test05()
{
	cout << "size of Person5 是:" << sizeof(Person5) << endl;
}

//结果还是4;
//静态成员函数也不属于对象。


//结论:只有非静态成员变量才属于对象。
//其余的都不归属于对象。

exp6:

class Person6
{
public:
	int m_Age;
	void func() {};
	static int m_B;
	static void func2() {};
	double m_C;

};

void test06()
{
	cout << "size of Person6 是:" << sizeof(Person6) << endl;
}

//答案是16,原因是字节对齐。
//****kkkk(int)+********(double)
 

int main()
{
    test01();
    test02();
    test03();
    test04();
    test05();
    test06();

    return 0;
}

//end

猜你喜欢

转载自blog.csdn.net/XUCHEN1230/article/details/84973365
今日推荐