结构体的使用方法(定义一个结构体)
#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使用时可以省略,第一第二中推荐,第三种不建议使用。
以上就是关于结构体的使用方法 相关问题啦,如需了解更多关于结构体的使用方法问题,关注我们的下次更新哦