在傳遞參數的時候,如果參數是string類型,可以用string類型的引用,減少內存的拷貝。
C++傳參盡量不用指針,防止弄亂(引用比指針簡單~~)
#include <iostream> using namespace std;//不要忘記聲明變量空間,不然無法使用string類型 void funcA( string& str){ cout << "傳引用 :str = " << str << endl; cout << "\"str\" 的地址: " << &str << endl; } void funcB(const string str){ cout << "傳值:str = " << str << endl; cout << "\"str\"的地址 : " << &str << endl; } int main(int agrc, char** argv){ string strInMain= "test"; funcA(strInMain);//傳引用, 減少內存的拷貝 funcB(strInMain);//傳值,傳遞的是實參的副本 cout << "strInMain = " << strInMain << endl; cout << "\"strInMain\"在主函數中的地址 : " << &strInMain << endl; cout <<strInMain; return 0; }
funA沒有拷貝變量,而是直接將main中的strInMain的地址傳入,所以在funA中的參數str的地址和main中strInMain的地址相同。因此可以在函數中對字符串修改,傳引用。
funB參數對strInMain進行拷貝,所以參數str的地址為新的內存空間,傳值
如果不想讓函數修改參數的值,只要把參數聲明為const常量即可
void func(const string& str){ cout << "str = " << str << endl; cout << "address of \"str\" : " << &str << endl; }