C++ structure overview | output structure variables

C++ structure overview

C++ provides many basic data types, but because the problems that programs need to deal with are often complex and diversified, the existing data types seem to be unable to meet the requirements of use.

Therefore, C++ allows programmers to declare some types by themselves. The types that programmers can declare by themselves include structure types, union types, enumeration types, class types, etc. These are all types that programmers can define by themselves.

A combination item contains several data items of different types. Both C language and C++ allow programmers to specify such a data type, which is called a structure.

C++ declares the general form of a structure type:

struct 结构体类型名
{
    
    成员表列}

When declaring a structure type, each member must be typed.

类型名 成员名;

Each member is also called a domain in the structure, and the member list is also called the domain table. The naming rules for member names are the same as those for variable names.

The position of declaring the structure type is generally at the beginning of the file, before all functions, so that all functions in this file can use it to define variables, and the structure type can also be declared in the function.

In the C language, the members of the structure can only be data. C++ has expanded on this basis. The members of the structure can include data and functions to adapt to object-oriented programming.

But because C++ provides class types, in general, structures with functions are not used.

Classic case: C++ uses structure variables.

#include<iostream>//预处理
using namespace std;//命名空间 
int main()//主函数 
{
    
    
  struct Student{
    
     //自定义结构体变量 
    int num;//学号 
    char sex;//性别 
    int age;//年龄 
  };
  struct Student str; 
  str.num=10001;//赋初值 
  str.sex='M';//赋初值 
  str.age=24;//赋初值 
  cout<<str.num<<endl;//输出学号 
  cout<<str.sex<<endl;//输出性别 
  cout<<str.age<<endl;//输出年龄 
  return 0; //函数返回值为0;
}

Compile and run results:

10001
M
24

--------------------------------
Process exited after 2.108 seconds with return value 0
请按任意键继续. . .

C++ output structure variables
More cases can go public account: C language entry to proficient

Guess you like

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