C++ member variables and member functions are stored separately

In C++, member variables and member functions in a class are stored separately.
Only non-static member variables belong to objects of the class

First take a look at how much space empty objects occupy:

#include <iostream>
using namespace std;
//成员变量和成员函数是分开存储的

class Person {
    
    



};


void test01() {
    
    
	Person p;

	cout << "size of p = " << sizeof(p) << endl;
}

int main() {
    
    

	test01();
	system("pause");
	return 0;
}

The result is size of p = 1;

The memory space occupied by empty objects is: 1

Why is it 1?
Because the C++ compiler also allocates a byte space for each empty object, in order to distinguish the memory location of the empty object.
Each empty object should also have a unique memory address, so the compiler will allocate a byte to each empty object as a distinction.

Now we give int m_A to the empty object and see what the result is?

code show as below:

#include <iostream>
using namespace std;
//成员变量和成员函数是分开存储的

class Person {
    
    
		int m_A;//非静态变量  属于类对象上的数据


};

void test01() {
    
    
	Person p;
	cout << "size of p = " << sizeof(p) << endl;

}


int main() {
    
    

	test01();
	system("pause");
	return 0;
}

The result is size of p = 4
Description: The
non-static variable m_A belongs to the object of the class

Now we go to static int m_B in the class and see what the result is?
void func()//Non-static function, what is the result?
What about static void func2()?

code show as below:

#include <iostream>
using namespace std;
//成员变量和成员函数是分开存储的

class Person {
    
    
		int m_A;
		static int m_B;//静态成员变量
		
		void func()
		{
    
    
		
		}
		static void func2()
		{
    
    
		
		}
};

int Person::m_B = 0;//静态成员变量特点,类内声明,类外初始化。不属于类对象上

void test01() {
    
    
	Person p;
	cout << "size of p = " << sizeof(p) << endl;

}


int main() {
    
    

	test01();
	system("pause");
	return 0;
}

The result is still: 4
1. Explain that the static member variable does not belong to the class object.
2. Explain that member functions (including static and non-static) are stored separately from member variables.

Each non-static member function will only produce a function instance, which means that multiple objects of the same type will share a piece of code. The question is:
how does this piece of code distinguish which object calls itself?

C++ solves the above problems by providing a special object pointer, this pointer.

Guess you like

Origin blog.csdn.net/m0_51955470/article/details/113100043