结构体虽然和数组一样,都可以存储多个数据项,但是在涉及到函数时,结构变量的行为更接近于一个基本的单值变量,也就是说,与数组不同,结构将其数据组合成单个实体或数据对象,该实体被视为一个整体。函数中参数为结构时,有三种方法:
1.直接将结构作为参数传递,并在需要时作为返回值返回。因此这种方法适用于结构比较小的情况。
例1:
- // travel.cpp -- using structures with functions
- #include <iostream>
- struct travel_time
- {
- int hours;
- int mins;
- };
- const int Mins_per_hr = 60;
- travel_time sum(travel_time t1, travel_time t2);
- void show_time(travel_time t);
- int main()
- {
- using namespace std;
- travel_time day1 = {5, 45}; // 5 hrs, 45 min
- travel_time day2 = {4, 55}; // 4 hrs, 55 min
- travel_time trip = sum(day1, day2);
- cout << "Two-day total: ";
- show_time(trip);
- travel_time day3= {4, 32};
- cout << "Three-day total: ";
- show_time(sum(trip, day3));
- // cin.get();
- return 0;
- }
- travel_time sum(travel_time t1, travel_time t2) //结构作为函数参数直接传入
- {
- travel_time total;
- total.mins = (t1.mins + t2.mins) % Mins_per_hr;
- total.hours = t1.hours + t2.hours +
- (t1.mins + t2.mins) / Mins_per_hr;
- return total;<span style="white-space:pre;"> </span>//结构作为函数结果直接传出
- }
- void show_time(travel_time t)
- {
- using namespace std;
- cout << t.hours << " hours, "
- << t.mins << " minutes\n";
- }
- // strctptr.cpp -- functions with pointer to structure arguments
- #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;
- cout << "Enter the x and y values: ";
- while (cin >> rplace.x >> rplace.y)
- {
- rect_to_polar(&rplace, &pplace); // pass addresses
- show_polar(&pplace); // pass address
- cout << "Next two numbers (q to quit): ";
- }
- cout << "Done.\n";
- return 0;
- }
- // show polar coordinates, converting angle to degrees
- void show_polar (const polar * pda)
- {
- using namespace std;
- const double Rad_to_deg = 57.29577951;
- cout << "distance = " << pda->distance;
- cout << ", angle = " << pda->angle * Rad_to_deg;
- cout << " degrees\n";
- }
- // convert rectangular to polar coordinates
- void rect_to_polar(const rect * pxy, polar * pda)<span style="white-space:pre;"> </span>//结构通过指针传入函数
- {
- using namespace std;
- pda->distance =
- sqrt(pxy->x * pxy->x + pxy->y * pxy->y);
- pda->angle = atan2(pxy->y, pxy->x); <span style="white-space:pre;"> </span>//通过在函数中修改结构的成员
- }
- 调用函数时,将结构的地址(&)而不是结构本身传递给它
- 将形参声明为指向poor的指针,由于函数不应该修改结构,因此使用了const
- 由于形参是指针而不是结构,因此应该用 间接成员运算符 (-> ),而不是成员运算符(.)
参考: c++中引用变量的使用
转自: https://blog.csdn.net/jyt1129/article/details/66973377