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; 
    }
  • 相关阅读:
    Linux/Unix 新手和专家教程
    恢复Ext3下被删除的文件
    如何调试bash脚本
    8个实用而有趣Bash命令提示行
    使用grep恢复被删文件内容
    一些非常有意思的杂项资源
    chmod -x chmod的N种解法
    纯文本配置还是注册表
    面向对象的Shell脚本
    你可能不知道的Shell
  • 原文地址:https://www.cnblogs.com/hemengjita/p/12814067.html
Copyright © 2011-2022 走看看