結(jié)構(gòu)體類型數(shù)據(jù)作為函數(shù)參數(shù)(三種方法)
(1)用結(jié)構(gòu)體變量名作為參數(shù)。
#include<iostream>
#include<string>
using namespace std;
struct Student{
string name;
int score;
};
int main(){
Student one;
void Print(Student one);
one.name="千手";
one.score=99;
Print(one);
cout<<one.name<<endl;
cout<<one.score<<endl;//驗證 score的值是否加一了
return 0;
}
void Print(Student one){
cout<<one.name<<endl;
cout<<++one.score<<endl;//在Print函數(shù)中,對score進行加一
}

這種方式值采取的“值傳遞”的方式,將結(jié)構(gòu)體變量所占的內(nèi)存單元的內(nèi)存全部順序傳遞給形參。在函數(shù)調(diào)用期間形參也要占用內(nèi)存單元。這種傳遞方式在空間和實踐上開銷較大,如果結(jié)構(gòu)體的規(guī)模很大時,開銷是很客觀的。
并且,由于采用值傳遞的方式,如果在函數(shù)被執(zhí)行期間改變了形參的值,該值不能反映到主調(diào)函數(shù)中的對應的實參,這往往不能滿足使用要求。因此一般較少使用這種方法。
(2)用指向結(jié)構(gòu)體變量的指針作為函數(shù)參數(shù)
#include<iostream>
#include<string>
using namespace std;
struct Student{
string name;
int score;
};
int main(){
Student one;
void Print(Student *p);
one.name="千手";
one.score=99;
Student *p=&one;
Print(p);
cout<<one.name<<endl;
cout<<one.score<<endl;//驗證 score的值是否加一了
return 0;
}
void Print(Student *p){
cout<<p->name<<endl;
cout<<++p->score<<endl;//在Print函數(shù)中,對score進行加一
}

這種方式雖然也是值傳遞的方式,但是這次傳遞的值卻是指針。通過改變指針指向的結(jié)構(gòu)體變量的值,可以間接改變實參的值。并且,在調(diào)用函數(shù)期間,僅僅建立了一個指針變量,大大的減小了系統(tǒng)的開銷。
(3)用接頭體變量的引用變量作函數(shù)參數(shù)
#include<iostream>
#include<string>
using namespace std;
struct Student{
string name;
int score;
};
int main(){
Student one;
void Print(Student &one);
one.name="千手";
one.score=99;
Print(one);
cout<<one.name<<endl;
cout<<one.score<<endl;//驗證 score的值是否加一了
return 0;
}
void Print(Student &one){
cout<<one.name<<endl;
cout<<++one.score<<endl;//在Print函數(shù)中,對score進行加一
}

實參是結(jié)構(gòu)體變量,形參是對應的結(jié)構(gòu)體類型的引用,虛實結(jié)合時傳遞的是地址,因而執(zhí)行效率比較高。而且,與指針作為函數(shù)參數(shù)相比較,它看起來更加直觀易懂。
因而,引用變量作為函數(shù)參數(shù),它可以提高效率,而且保持程序良好的可讀性。
相關(guān)文章
完全掌握C++編程中構(gòu)造函數(shù)使用的超級學習教程
這篇文章主要介紹了C++中的構(gòu)造函數(shù),包括C++11標準中的新特性的介紹,十分推薦!需要的朋友可以參考下2016-01-01
Visual Studio Code (vscode) 配置 C / C++ 環(huán)境的流程
這篇文章主要介紹了Visual Studio Code (vscode) 配置 C / C++ 環(huán)境的流程,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
C語言數(shù)據(jù)結(jié)構(gòu)實例講解單鏈表的實現(xiàn)
單鏈表是后面要學的雙鏈表以及循環(huán)鏈表的基礎(chǔ),要想繼續(xù)深入了解數(shù)據(jù)結(jié)構(gòu)以及C++,我們就要奠定好這塊基石!接下來就和我一起學習吧2022-03-03
C語言 數(shù)據(jù)結(jié)構(gòu)鏈表的實例(十九種操作)
這篇文章主要介紹了C語言 數(shù)據(jù)結(jié)構(gòu)鏈表的實例(十九種操作)的相關(guān)資料,需要的朋友可以參考下2017-07-07
Linux環(huán)境g++編譯GDAL動態(tài)庫操作方法

