C++ Note 12: C++ Extension to C - struct keyword type enhancement

A struct in the C language defines a collection of variables, which the C compiler does not consider a new type.

 

A struct in C++ is a definition declaration of a new type.

 

struct Student

{

char name[100];

int age;

};

void main()

{

Student s1={"wang",1};

Student s2={"wang",2};

}

 

 

In the above program, we use the .c file to compile and report an error.

At this time, the c compiler does not think that Student is a new type, we must add the struct keyword in front of Student!

 

struct Student

{

char name[100];

int age;

};

void main()

{

struct Student s1={"wang",1};

struct Student s2={"wang",2};

}

 

 

C++ has enhanced the struct keyword.

We put the same program that cannot be compiled under the c compiler into the .cpp file and found that it can be compiled! That is to say, in C++, it is considered that struct defines a new type, and this new type can be used to define new variables.

 

 

#include<iostream>

using namespace std;

 

struct Student

{

char name[100];

int age;

};

void main()

{

Student s1={"wang",1};

Student s2={"wang",2};

system("pause");

}

 

 

In addition, C++ not only enhances the type of the struct keyword, but the struct keyword and the class keyword perform the same functions. Of course, there are also differences. The difference will be discussed later.

You can also add access data permissions to the structure: public, protected, etc.

 

 

#include<iostream>

using namespace std;

 

struct Student

{

public:

char name[100];

int age;

private:

int a;

};

void main()

{

struct Student s1

system("pause");

}

 

 

 

 

 

long press to unlock

 

Unlock more exciting insider

 

programming according to the law

WeChat: Lightspeed-Tech

Technology drives life

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325116461&siteId=291194637