How to use the structure struct of C++
This article mainly explains "how to use the struct of C++". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the struct of C++.
Struct structure occupies space
The hollow structure occupies 1 byte in C++
Struct Temp {}; sizeof (Temp); / / 1struct Temp {}; sizeof (Temp); / / 1
1. Byte alignment rule (for cpu addressing) the first address of an element must be an integral multiple of the space occupied by the current element
two。 The total length of the structure must be an integral multiple of the space occupied by the largest element.
Struct Stu {int age;char sex;} sizeof (Stu); / 8 the last three bytes satisfy the rule 2struct Stu2 {char sex;int age;} sizeof (Stu2); / 8 the last three bytes of char satisfy the rule 1struct Stu {int age;char sex;} sizeof (Stu); / 8 the last three bytes satisfy the rule 2struct Stu2 {char sex;int age;} sizeof (Stu2) / / 8 the following three bytes of char satisfy the difference between rule 1 and class access control permissions
The default access control permission for structures in C++ is * * public***, while the default for class is * private***.
Main use
The structure is mainly used as a collection of data
And a class is an object, a collection of properties and methods.
C structure realizes the function of virtual function # include typedef int (* fun) (void); int getParentSex () {return 1;} int getSonSex () {return 2;} struct Parent {fun getSex;}; struct Son {fun getSex;}; int main () {/ / achieves the function of virtual function struct Parent parent; parent.getSex = getParentSex; struct Son son; son.getSex = getSonSex through the assignment of function pointer Printf ("Parent sex is% d\ nson sex is% d\ n", parent.getSex (), son.getSex ()); getchar ();} Thank you for your reading. The above is the content of "how to use the structure struct of C++". After the study of this article, I believe you have a deeper understanding of how to use the structure struct of C++, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!