C++ Classes and Structures | Classes and Structure Types

C++ classes and structure types

C++ is different from the C language. After adding the class type on the basis of the C language, the structure type struct is still retained, and its function is also extended, allowing the use of struct to define a type, and the keyword class can be used before The declared class type is changed to use the keyword struct:

struct Student //用struct来声明一个类类型 
{
    
    
  private: //声明以下为私有的 
    int number; //学号 
    char name[10];//姓名 
    char sex; //性别 
  public: //声明以下为共有的 
    void print_info() //打印 
    {
    
    
      cout<<number<<endl;
      cout<<name<<endl;
      cout<<sex<<endl;
    };
}
Student stu1,stu2;//定义了Student类对象

C++ does not simply inherit the structure of the C language, but makes it also have the characteristics of a class, so that it can be used in object-oriented programming, so that the structure type also has the characteristics of encapsulation.

The structure type declared with struct in C++ is actually a class. If its members are not declared private or public, the system will default to public; if you want to specify private and public members separately, use private or public as Explicitly declare.

For a class defined by class, if you do not make a private or public declaration, the system will default its members to private, and you can change it with an explicit declaration when needed.

If you want the members to be public, it is more convenient to use struct; if you want some members to be private, you should use class. It is recommended that readers try to use class to create classes, which is more in line with the C++ style.

C++ classes and structures
More cases can go to the public account: C language entry to proficient

Guess you like

Origin blog.csdn.net/weixin_48669767/article/details/112748385