结构变量的行为更接近于基本的单值变量。也就是说,与数组不同,结构将其数据组合成单个实体或数据对象,该实体 被视为一个整体。
但是按值传递有一个缺点:如果结构非常大,那么复制结构就会增加内存需求,降低运行速度。
1.直接传递和返回结构
定义一个结构。
struct travle_time{ int hours; int mins; }
可以直接传递到函数中,然后再返回。
void show_time(travle_time t){ using namespace std; cout << t.hours << " hours," << t.mins << " minutes \n "; }
这种方式,函数直接从内存中复制出了一份结构体,在函数中作为局部变量单独使用
2.传递结构的地址
- 调用函数时候,需要将结构的地址(&travle_time)而不是结构本身(travle_time)传递给他;
- 将形参声明为指向travle_time的指针,即travle_time * 类型。由于函数不应该修改结构内容,因此使用const修饰符;
- 由于形参是指针而不是结构,因此应该使用间接成员运算符(->),而不是成员运算符(句点)。
void show_time(travle_time t){ using namespace std; cout << t->hours << " hours," << t->mins << " minutes \n "; }
3.传递结构地址,并返回结构。
在调用函数之前声明好函数返回的结构,在函数传参的时候做为一个形参(同样是结构地址,但是不要加const),在函数体重对其进行赋值。
#include <iostream> #include <cmath> // structure templates struct polar { double distance; // distance from origin double angle; // direction from origin }; struct rect { double x; // horizontal distance from origin double y; // vertical distance from origin }; // prototypes void rect_to_polar(const rect * pxy, polar * pda); void show_polar (const polar * pda); int main() { using namespace std; rect rplace; polar pplace; // 在调用函数之前声明好函数返回的结构即可。 rect_to_polar(&rplace, &pplace); return 0; } void rect_to_polar(const rect * pxy, polar * pda) { using namespace std; pda->distance = sqrt(pxy->x * pxy->x + pxy->y * pxy->y); pda->angle = atan2(pxy->y, pxy->x); }