結構體類型數據作為函數參數(三種方法)---轉


    將一個結構體變量中的數據傳遞給另一個函數,有下列3種方法:

  1. 用結構體變量名作參數。一般較少用這種方法。
  2. 用指向結構體變量的指針作實參,將結構體變量的地址傳給形參。
  3. 用結構體變量的引用變量作函數參數。

   下面通過一個簡單的例子來說明,並對它們進行比較。

  有一個結構體變量stu,內含學生學號、姓名和3門課的成績。要求在main函數中為各成員賦值,在另一函數print中將它們的值輸出。

 

 1) 用結構體變量作函數參數。

  

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;  4 struct Student//聲明結構體類型Student
 5 {  6    int num;  7    char name[20];  8    float score[3];  9 }; 10 int main( ) 11 { 12    void print(Student); //函數聲明,形參類型為結構體Student
13    Student stu; //定義結構體變量 
14    stu.num=12345; //以下5行對結構體變量各成員賦值
15    stu.name="Li Fung"; 16    stu.score[0]=67.5; 17    stu.score[1]=89; 18    stu.score[2]=78.5; 19    print(stu); //調用print函數,輸出stu各成員的值
20    return 0; 21 } 22 void print(Student st) 23 { 24    cout<<st.num<<" "<<st.name<<" "<<st.score[0] 25    <<" " <<st.score[1]<<" "<<st.score[2]<<endl; 26 }

 

  2)用指向結構體變量的指針作實參在上面程序的基礎上稍作修改即可。

  

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;  4 struct Student  5 {  6    int num; string name; //用string類型定義字符串變量
 7    float score[3];  8 }stu={12345,"Li Fung",67.5,89,78.5}; //定義結構體student變量stu並賦初值
 9 int main( ) 10 { 11    void print(Student *); //函數聲明,形參為指向Student類型數據的指針變量
12    Student *pt=&stu; //定義基類型為Student的指針變量pt,並指向stu
13    print(pt); //實參為指向Student類數據的指針變量
14    return 0; 15 } 16 
17 //定義函數,形參p是基類型為Student的指針變量
18 void print(Student *p) 19 { 20    cout<<p->num<<" "<<p->name<<" "<<p->score[0]<<" " <<
21    p->score[1]<<" "<<p->score[2]<<endl; 22 }

 

  調用print函數時,實參指針變量pt將stu的起始地址傳送給形參p(p也是基類型為student的指針變量)。這樣形參p也就指向stu

在print函數中輸出p所指向的結構體變量的各個成員值,它們也就是stu的成員值。在main函數中也可以不定義指針變量pt,而在調用print函數時以&stu作為實參,把stu的起始地址傳給實參p。

 

 3) 用結構體變量的引用作函數參數

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;  4 struct Student  5 {  6    int num;  7    string name;  8    float score[3];  9 }stu={12345,"Li Li",67.5,89,78.5}; 10 
11 int main( ) 12 { 13    void print(Student &); 14    //函數聲明,形參為Student類型變量的引用
15  print(stu); 16    //實參為結構體Student變量
17    return 0; 18 } 19 
20 //函數定義,形參為結構體Student變量的引用
21 void print(Student &stud) 22 { 23    cout<<stud.num<<" "<<stud.name<<" "<<stud.score[0] 24    <<" " <<stud.score[1]<<" "<<stud.score[2]<<endl; 25 }

 

程序(1)用結構體變量作實參和形參,程序直觀易懂,效率是不高的。
程序(2)采用指針變量作為實參和形參,空間和時間的開銷都很小,效率較高。但程序(2)不如程序(1)那樣直接。
程序(3)的實參是結構體Student類型變量,而形參用Student類型的引用,虛實結合時傳遞的是stu的地址,因而效率較高。它兼有(1)和(2)的優點。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM