C++系列--成员变量和成员函数的存储

  • 空对象所占的内存为1,是为了区分空对象所占的内存位置。
  • 非空对象所占的内存按照实际的来。
  • 非静态成员变量属于类的对象上面。
  • 非静态成员函数和静态成员函数,静态成员变量都不属于类的成员上。
cpp 复制代码
空对象所占的内存为1,是为了区分空对象所占的内存位置。
code:
	#include<iostream>
	using namespace std;
	class City
	{
	public:
	
	};
	void main()
	{
		City c1;
		cout << "空对象所占的内存:" << sizeof(c1) << endl;
		system("pause");
	};
result:
空对象所占的内存:1
cpp 复制代码
非空对象按照实际的内存来,非静态成员变量存在于类的对象上,静态成员不属于类的对象上。
code:
	#include<iostream>
	using namespace std;
	class City
	{
	public:
		int num = 2;
		static int s_num;	// 不属于类的对象上
	};
	int City::s_num = 5;
	void main()
	{
		City c1;
		cout << "对象所占的内存:" << sizeof(c1) << endl;
		system("pause");
	};
result:
	所占的内存:4
cpp 复制代码
非静态成员函数和静态成员函数都不属于类的成员上
code:
	#include<iostream>
	using namespace std;
	class City
	{
	public:
		int num = 2;
		static int s_num;
		void show_value()
		{
			cout << num << endl;
		}
		static void s_show_value()
		{
			cout << s_num << endl;
		}
	};
	int City::s_num = 5;
	void main()
	{
		City c1;
		cout << "对象所占的内存:" << sizeof(c1) << endl;
		system("pause");
	}
result:
	所占的内存:4
相关推荐
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
学Linux的语莫9 天前
python基础语法
开发语言·python
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
小灰灰搞电子9 天前
Qt PyQt与PySide技术-C++库的Python绑定
c++·qt·pyqt
暖馒9 天前
C#委托与事件的区别
开发语言·c#
嘉琪0019 天前
2025——js 面试题
开发语言·javascript·ecmascript
Jinxiansen02119 天前
Vue3 中 ref 与 reactive 使用场景总结(含对比与示例)
开发语言·javascript·ecmascript
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
止观止9 天前
Rust智能指针演进:从堆分配到零复制的内存管理艺术
开发语言·后端·rust