1. 程式人生 > >C++ 字串 14-- 18.40.結構體與函式 結構體作為函式引數、結構體指標作為函式返回值

C++ 字串 14-- 18.40.結構體與函式 結構體作為函式引數、結構體指標作為函式返回值

#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
18.40.結構體與函式
 結構體作為函式引數、結構體指標作為函式返回值
---------------------------------*/
struct time{
	int hour;
	int minute;
};
const int perhour=60;
time* sum(time t1,time t2);
void show(time t);
int main()
{
	time one={8,15};
	time two={6,46};
	time *day=sum(one,two);//與上一節不同的是,這裡只是返回結構體的地址
	show(one);			   //因此,不用呼叫複製建構函式複製返回的結構體
	show(two);
	cout<<"兩天的時間總計:";
	show(*day);
	time three={2,12};
	show(three);
	cout<<"三天的時間總計:";
	time *day2=sum(*day,three);
	show(*day2);
	delete day; //在函式sum()中申請的記憶體得釋放
	delete day2;//在函式sum()中申請的記憶體得釋放
	return 0;
}
time* sum(time t1,time t2)
{
	time *total=new time;
	total->minute=(t1.minute+t2.minute)%perhour;
	total->hour=t1.hour+t2.hour+(t1.minute+t2.minute)/perhour;
	return total;
}
void show(time t)
{
	cout<<"hour:"<<t.hour<<"\tminute:"<<t.minute<<endl;
}
/*
執行結果:
hour:8  minute:15
hour:6  minute:46
兩天的時間總計:hour:15 minute:1
hour:2  minute:12
三天的時間總計:hour:17 minute:13
Press any key to continue
*/



#include <string.h>
#include <stdio.h>
#include <stdlib.h>//malloc所在標頭檔案
/*---------------------------------
18.40.結構體與函式
 結構體作為函式引數、結構體指標作為函式返回值
---------------------------------*/
typedef struct {  //C語言中定義結構體跟C++中略有區別
	int hour;
	int minute;
}time;
const int perhour=60;//或者按照以下方式
//#define perhour 60
//time* sum(time& t1,time& t2);//【【【【【【【【C語言不支援 引用傳遞引數】】】】】】】】】
time* sum(time t1,time t2);
void show(time t);
int main()
{
	time one={8,15};
	time two={6,46};
	time *day=sum(one,two);//與上一節不同的是,這裡只是返回結構體的地址
	show(one);			   //因此,不用呼叫複製建構函式複製返回的結構體
	show(two);
	printf("兩天的時間總計:\n");
	show(*day);
	free(day); //在函式sum()中申請的記憶體得釋放
	return 0;
}
time* sum(time t1,time t2)
{
	time *total=(time*)malloc(sizeof(time));
	total->minute=(t1.minute+t2.minute)%perhour;
	total->hour=t1.hour+t2.hour+(t1.minute+t2.minute)/perhour;
	return total;
}
void show(time t)
{
	printf("hour:%d",t.hour);
	printf("\tminute:%d\n",t.minute);
}
/*
執行結果:
hour:8  minute:15
hour:6  minute:46
兩天的時間總計:
hour:15 minute:1
Press any key to continue
*/