龙空技术网

c++结构体的定义与使用

白同学 113

前言:

当前各位老铁们对“结构体的定义和使用”大致比较注重,姐妹们都需要学习一些“结构体的定义和使用”的相关内容。那么小编也在网络上收集了一些关于“结构体的定义和使用””的相关内容,希望同学们能喜欢,兄弟们快快来学习一下吧!

#include<iostream>

using namespace std;

#include<ctime>

#include<string>

struct student

{

string name;//放入变量

int age;

int score;

};//定义结构体

int main()

{

struct student s1;//结构体变量

s1.age=20;//变量赋值

s1.name="sd";

s1.score=90;

cout <<"xingming:"<<s1.name<<endl;

system("pause");

return 0;

}

定义结构体直接放入数据

#include<iostream>

using namespace std;

#include<ctime>

#include<string>

struct student

{

string name;

int age;

int score;

};//定义结构体

int main()

{

struct student s2= { "sd", 90 };//定义结构体的时候直接放入数据

cout <<"xingming:"<<s2.name<<endl;

system("pause");

return 0;

}

定义结构体时,创建结构体变量

#include<iostream>//头文件

using namespace std;//引用命名空间

#include<ctime>//时间头文件

#include<string>//字符串头文件

struct student//定义结构体

{

string name;//数据类型 定义变量(字符串型)

int age;//数据类型 定义变量(整形)

int score;//数据类型 定义变量(整形)

}s1;//定义结构体创建变量

int main()

{

s1.name="sd";//给变量赋值

s1.score=90;

s1.age=20;

cout <<"xingming:"<<s1.name<<endl;

system("pause");

return 0;

}

比较三种区别,只是逻辑不一样,其实差不多。struct使用时可以省略,第一第二中推荐,第三种不建议使用。

标签: #结构体的定义和使用