当前位置:网站首页>Classes and Structures

Classes and Structures

2022-08-09 07:04:00 Want to be the front end of the back end

Classes and Structures in C++

In C++, a struct is a special kind of class.
The only difference between a structure and a class is: Structures and classes have different default access control properties.

  • In the class, for members without specified access control attributes, their access control attributes are private type (private)
  • In the structure, for members that do not specify any access control attributes, their access control attributes are public type (public)

In C++, the absence of structures does not affect the expressiveness of the program at all.The reason why C++ introduces structures is to maintain compatibility with C programs.
But sometimes structures are still used in C++, because structures can be used to combine different types of data into a whole, which is convenient for saving data.(If you use a class to save, because the members in the class are private by default, it is more troublesome to read and rewrite each attribute with a specific function for each data member.)

Structure in C

Structures in C language are not allowed to define function members, and there is no concept of access control attributes.
C++ introduces object-oriented features such as member functions, access control rights, inheritance, and polymorphism to structures in C language.
C++ introduces the class keyword in addition to struct, but in order to maintain compatibility with C programs, C++ retains the struct keyword and specifies that the default access control authority of the structure is a public type.
In addition, in the C language, the size of an empty structure is 0, while the size of a C++ hollow structure (belonging to an empty class) is 1.
The reason why the size of an empty class in C++ is 1:
Empty classes can also be instantiated, and each object instantiated by the class needs to have a different memory address.The address is different in the class, so an implicit byte is added to the class.

原网站

版权声明
本文为[Want to be the front end of the back end]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090659393209.html