zoukankan      html  css  js  c++  java
  • 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; 
    }
  • 相关阅读:
    各种算法时空复杂度
    Python文本处理(1)
    数学之路(3)-机器学习(3)-机器学习算法-欧氏距离(3)
    为什么要选择cdn加速
    数据库中操作XML(openXML)
    HDU 3308 LCIS
    Android有效解决加载大图片时内存溢出的问题
    Pathchirp—有效的带宽估计方法(二)
    php三元运算
    C# MVC 自学笔记—4 添加视图
  • 原文地址:https://www.cnblogs.com/hemengjita/p/12814067.html
Copyright © 2011-2022 走看看