除了傳遞一般變數外
也可以將結構傳入函數中
可以自行選擇要傳遞整個結構或是特定欄位
將整個結構傳遞到函數
直接將整個結構變數函數時
就像平常一樣
以傳值呼叫的方式傳遞
函數宣告
傳回值型態 函數名稱(struct 結構名稱);
函數定義
傳回值型態 函數名稱(struct 結構名稱1 變數1){
……….
}
函數呼叫
函數呼叫
函數名稱(結構名稱);
Ex:
#include <iostream> #include <string> using namespace std; struct student { string name; string id; int math; int eng; }; void show(struct student); //函數原型宣告 int main() { struct student s1={"Tony","AMA104143",70,60}; //建立物件並且初始化 show(s1); //呼叫函數,印出所有欄位 } //函數定義 void show(struct student a){ cout << "name=" << a.name << endl; cout << "id=" << a.id << endl; cout << "math=" << a.math << endl; cout << "english=" << a.eng << endl; }
將特定欄位傳遞到函數
跟一般函數一樣
傳入該欄位的值
函數宣告
傳回值型態 函數名稱(型態1,型態2……);
函數定義
傳回值型態 函數名稱(型態1 引數1 ,型態2 引數2……){
……….
}
函數呼叫
函數名稱(引數1 ,引數2……);
Ex:
#include <iostream> #include <string> using namespace std; struct student { string name; string id; int math; int eng; }; void sum(int,int); //函數原型宣告 int main() { struct student s1={"Tony","AMA104143",70,60}; //建立物件並且初始化 sum(s1.math,s1.eng); //呼叫函數,算出總和 } //函數定義 void sum(int a,int b){ int sum=0; sum=a+b; cout << "sum=" << sum <<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>< endl; }