1 // C++函数和类 12-函数与结构体.cpp: 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <string> 7 #include <climits> 8 #include <math.h> 9 #include <array> 10 using namespace std; 11 12 struct WorkTime 13 { 14 int hours; 15 int mins; 16 }; 17 WorkTime sum(WorkTime t1, WorkTime t2); 18 const int Mins_per_hour = 60; 19 int main() 20 { 21 WorkTime morning = { 2,40 }; 22 WorkTime afternoon = { 6,40 }; 23 WorkTime day = sum(morning , afternoon); 24 cout << "一天一共工作了:" << day.hours << "小时," << day.mins << "分钟。" << endl; 25 return 0; 26 } 27 28 //结构体在函数中可以和某个类型一样使用,作为参数传递或者作为返回值返回 29 //结构体较大时,为了避免赋值副本,可以使用指针或引用类型 30 WorkTime sum(WorkTime t1, WorkTime t2) 31 { 32 WorkTime total; 33 total.mins = (t1.mins + t2.mins)%Mins_per_hour; 34 total.hours = t1.hours + t2.hours + (t1.mins + t2.mins) / Mins_per_hour; 35 return total; 36 }