C++中 string作為參數的傳遞(傳引用,減少內存的拷貝;const參數 )


在傳遞參數的時候,如果參數是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; 
}

 


免責聲明!

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



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