为结构编写函数

结构变量行为更像单值变量而非数组

因为结构将其中数据组合成单个实体或者数据对象,该实体被视为一个整体

函数返回结构的方式:

  1.按值传递结构(将结构作为参数传递并返回结构)

    适用于结构较小时

    缺:结构大时,内存占用大

  2.传递结构地址,并且使用指针访问结构内容

  3.按引用传递

  注:返回结构式要获得结构的地址,结构名只是结构的名称,要获得结构的地址必须使用&

案例:

 1 #include<iostream>
 2 using namespace std;
 3 struct travel_time
 4 {
 5     int hours;
 6     int mins;
 7 };
 8 //记得加函数声明
 9 travel_time sum(travel_time, travel_time);
10 int main()
11 {
12     travel_time TB = { 3, 50 };
13     travel_time BG = { 1,25 };
14     //travel_time total_main=travel_time sum(TB, BG);
15     //调用函数时都不要写出函数类型
16     travel_time total_main = sum(TB, BG);
17     /*cout << travel_time total_main.hours << endl;*/
18     //调用结构的对象时也不用写出结构名
19     cout << total_main.hours << endl;
20     cout << total_main.mins << endl;
21 
22 }
23 travel_time sum(travel_time t1, travel_time t2)
24 {
25     /*sum.hours = t1.hours + t2.hours;*/
26     //并不是直接将两个结构中内容加给sum这个函数名!你要再创建一个结构的对象,这个结构在函数结束时确实会被释放,但是只需要把它的内容返回就好
27     travel_time total_fun;
28     int temp1 = t1.hours + t2.hours;
29     int temp2= t1.mins + t2.mins;
30     total_fun.mins = temp2 % 60;
31     total_fun.hours = temp1 + temp2 / 60;
32     return total_fun;
33 }

 按引用传递结构:

对于:

 

struct polar
{
    ...
}

int main()
{
    polar pplace;
    ...
    return 0;
}

void show_polar (const polar *pda)
{
    ...
}

 

调用函数时,将结构对象的地址(&pplace)而不是结构对象本身传递给他

将传递给函数的形参设置为(结构名*形参名)

形参是指针不是结构,所以在函数中应使用->而非直接成员运算符(.)

 1 #include<iostream>
 2 using namespace std;
 3 //第一种:传递结构地址且修改结构的内容
 4 
 5 //第二种:传递结构地址但是不修改结构内容
 6 struct rect //原始结构
 7 {
 8     double x;
 9     double y;
10 };
11 struct polar //存放运算完结果的结构
12 {
13     double distance;
14     double angle;
15 };
16 void rect_to_polar(const rect* pxy, polar* pda);
17 
18 int main()
19 {
20     rect rplace;
21     polar pplace;
22     //...
23     rect_to_polar(&rplace, &pplace);
24     //...
25 }
26 void rect_to_polar(const rect* pxy, polar* pda)
27 {
28     //使用pxy的数据,并合理利用'->'存入pda中(所以第一个形参是const第二个不是)
29 }

 

posted @ 2022-04-05 16:08  卷卷卷卷出一片天  阅读(48)  评论(0)    收藏  举报