c++ 8、结构体
2020-05-10 本文已影响0人
八戒无戒
1、结构以定义
typedef struct
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
示例:
typedef struct
{
char[50] title;
char[500] desc;
int id;
}Book;
2、访问结构成员
成员访问运算符.
访问:
结构体指针->
访问:
有如下代码>>>>>>:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
typedef struct
{
string title;
string desc;
int id;
}Book;
int main()
{
Book book1;
Book book2;
// 成员运算符访问
book1.title = "三国演义";
book1.desc = "乱世争霸";
book1.id = 1;
// 指针访问
Book *p;
p = &book2;
p->title = "水浒传";
p->desc = "梁山起义";
p->id = 2;
cout << book1.title << endl;
cout << book2.title << endl;
return 0;
}
运行结果:
三国演义
水浒传
3、结构体传参
函数可以将结构体当作参数转递,也可将结构体指针当作参数进行传递。需要注意的是,当结构体作为形参参入函数时,是无法真正改变结构体内部的值的
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
typedef struct
{
string title;
string desc;
int id;
}Book;
extern void PrintBook(Book book); // 此种传参无法改变book结构体的值
extern void PrintBook(Book *book);
int main()
{
Book book1;
Book book2;
Book *p;
p = &book2;
book1.title = "海底两万里";
book1.desc = "海底探险";
book1.id = 3;
book2.title = "钢铁是怎样炼成的";
book2.desc = "小男孩的成长史";
book2.id = 4;
PrintBook(book1);
PrintBook(p);
return 0;
}
void PrintBook(Book book)
{
cout << book.title << endl;
cout << book.desc << endl;
cout << book.id << endl;
}
void PrintBook(Book *book)
{
cout << book->title << endl;
cout << book->desc << endl;
cout << book->id << endl;
}
运行结果:
海底两万里
海底探险
3
钢铁是怎样炼成的
小男孩的成长史
4