The following five columns are only available for C ++ and do not involve sizeof bytes alignment and basic data types.
Using sizeof in C ++ is much more complex than C, because the C ++ class contains static variables, virtual functions, inheritance, and derivation. Sizeof is a single-object operator in C language, such as other operators ++ and -- in C language. It is not a function. The sizeof operator provides the storage size of its operands in bytes.
Sizeof can be used in three forms: sizeof (var_name), sizeof var_name, or sizeof (var_type ).
[Example 1]: (structure and destructor are ignored in the column)
Copy codeThe Code is as follows:
Class
{
Public:
Void hello (){}
};
Sizeof (A) = 1;
It must not be zero. For example, if it is zero, declare an array of class A [10] objects, and each object occupies zero space. In this case, a [0] cannot be distinguished. A [1]… .
Because A is an empty class and occupies 1 byte to distinguish two different objects, it can also be seen as A placeholder. The address of this byte is the address of the object. But here 1 is not absolute, just the compiler setting.
[Example 2 ]:
Copy codeThe Code is as follows:
Class B
{
Public:
Void hello (){}
Static int I;
};
Sizeof (B) = 1;
Because static variables are shared among classes, space is allocated in the static zone, and space is allocated during compilation without occupying class memory.
[Example 3 ]:
Copy codeThe Code is as follows:
ClassC
{
Public:
Virtual void hello (){}
};
Sizeof (C) = 4;
Class B has virtual functions, and corresponding virtual table pointers exist, occupying 4 bytes, which is exactly the space of a pointer. At the same time, if multiple virtual functions or multiple classes inherit the C class, the virtual functions only occupy 4 bytes, such as [Example 4 ]:
[Example 4 ]:
Copy codeThe Code is as follows:
Class D: public C
{
Public:
Virtual void world (){}
Virtual void nihao (){}
};
Sizeof (D) = 4;
[Example 5 ]:
Copy codeThe Code is as follows:
Class E
{
Public:
Virtual void hello (){}
Virtual void world (){}
Staticint I;
Static int j;
Int k;
};
Sizeof (E) = 8;
Hope to help you.