struct 结构体名
{
数据成员
成员函数
};
// 定义一个结构体
struct Person {
// 成员变量
std::string name;
int age;
double height;
};
第一种定义结构体变量:struct Person person1;此时person1为结构体变量;或者Person person1也可以;
struct Student
{
char name[12];
int age;
}stu1;此时stu1为第二种定义结构体变量;
#include <bits/stdc++.h>
using namespace std;
/*定义Student结构体,包括字符数组name,年龄变量age;同时按照第二种方式定义结构体变量stu1*/
struct Student
{
char name[12];
int age;
}stu1;
int main()
{
strcpy(stu1.name, "xiaowang");//将字符串xiaowang拷贝给stu1的name。
stu1.age = 15;//给stu1的年龄赋值15.
printf("%s %d\n", stu1.name, stu1.age);//输出stu1的姓名,年龄,以空格隔开。
/*定按照第一种方式定义结构体变量stu2*/
struct Student stu2;
strcpy(stu2.name, "lisi");//将字符串lisi拷贝给stu2的name。
stu2.age = 10;//给stu2的年龄赋值10.
printf("%s %d\n", stu2.name, stu2.age);//输出stu2的姓名,年龄,以空格隔开。
return 0;
}此时的stu2与stu1都是结构体变量,但是不是同一个结构体了;
struct Person
{
char name[16];
int age;
}*p,per;此时*p为结构体指针;
使用结构体指针变量,给姓名拷贝xiaoming,年龄赋值16,输出姓名,年龄,空格隔开。
strcpy(p->name,"xiaoming"); p->age=16;
typedef的作用:
typedef int Integer; // 为 int 创建别名 Integer
typedef double Real; // 为 double 创建别名 Real
//结构体的别名:
struct Person {
string name;
int age;
};
typedef Person Employee; // 将 Person 结构体创建别名 Employee
int main() {
Employee employee1;又将employee1定义为结构体变量;
employee1.name = "Alice";
//用typedef关键字,就代表 per 等价于 struct Person,perptr 等价于 struct Person*。
#include<iostream>
using namespace std;
typedef struct Person
{
char name[16];
int age;
}per, *perptr;
int main()
{
per a; 又使用别名将a定义为结构体变量;
strcpy(a.name, "xiaomi");
a.age = 7;
cout<<a.name<<" "<<a.age<<endl;
//------------------------------------//
per *q;
q = new Person[sizeof(struct Person)];
strcpy(q->name, "xiaobai");
q->age = 8;
cout<<q->name<<" "<<q->age<<endl;
delete q;
//------------------------------------//
perptr p;
p = new Person[sizeof(struct Person)];
strcpy(p->name, "xiaotao");
p->age = 9;
cout<<p->name<<" "<<p->age<<endl;
delete p;
return 0;
660




被折叠的 条评论
为什么被折叠?



