從函數回傳物件

函數宣告
類別名稱 函數名稱(類別名稱);

函數定義

 

類別名稱 函數名稱(類別名稱1 引數1 ,類別名稱2 引數2 ,…….){
          …………..
}

 

函數呼叫
函數名稱(物件名稱);

 

Ex:

 

[code language=”cpp”]
#include <iostream>
using namespace std;

class time
{
public:
int hour;
};

void show(time);

//函數原型宣告
time compare(time,time);

int main(){

time t1,t2,t3;

t1.hour=10;
t1.hour=15;

show(t1);
show(t2);

t3=compare(t1,t2); //呼叫函數,傳入物件t1,t2,並且將回傳的物件指定給t3

show(t3); //印出物件t3內容

}

void show(time t){

cout << "hour=" << t.hour << endl; } //函數定義 time compare(time t1,time t2){ if(t1.hour>t2.hour)
return t1;
else
return t2;

}<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>
[/code]

 

有疑問? 留個言吧!

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

%d 位部落客按了讚: