定义结构
struct Peoples
{
string name;
string sex;
int age;
} people;
访问成员
#include <iostream>
using namespace std;
//定义一个books的数据结构
struct Peoples{
string name;
string sex;
int age;
};
int main( )
{
Peoples people1;
people1.name="张三";
people1.sex="男";
people1.age=23;
cout<<"姓名为:"<<people1.subject<<endl;
cout<<"性别为:"<<people1.title<<endl;
cout<<"年龄为:"<<people.book_id<<endl;
return 0;
}
数据结构作为函数参数
#include <cstdio>
#include <iostream>
using namespace std;
//声明一个函数
void printPeople(struct Peoples people);
//定义一个books的数据结构
struct Peoples{
string name;
string sex;
int age;
};
int main( )
{
Peoples people1;
people1.name="张三";
people1.sex="男";
people1.age=23;
printPeople(people1);
return 0;
}
void printPeople(struct Peoples people){
cout<<"姓名为:"<<people.name<<endl;
cout<<"性别为:"<<people.sex<<endl;
cout<<"年龄为:"<<people.age<<endl;
}
指向结构的指针
形式:struct Peoples *struct_pointer;
使用&运算符查找结构变量的地址。
使用->运算符访问结构的成员。
实例:
#include <iostream>
#include <cstring>
using namespace std;
void printPeople( struct Peoples *people);
struct Peoples
{
string name;
string sex;
int age;
};
int main( )
{
Peoples people;
people.name="张三";
people.sex="男";
people.age=23;
printPeople( &people );
return 0;
}
// 该函数以结构指针作为参数
void printPeople( struct Peoples *people )
{
cout << "姓名 : " << people->name<<endl;
cout << "性别 : " << people->sex<<endl;
cout << "年龄 : " << people->age<<endl;
}
typedef关键字
typedef struct Peoples
{
string name;
string sex;
int age;
}Peoples;
typedef关键字可以用来定义非结构类型:typedef long int *pint32; pint32 x,y,z;
x,y,z都是指向长整型long int 的指针。