c++ 函数传参 string string& const string &三者的区别

1.string做参数:

#include <bits/stdc++.h>
using namespace std;
void test(string s){
    s="shit";
}
int main(){
    string s{"test"};
    test(s);
    cout<<s<<endl;
}

打印结果:

test

2.string&做参数:

void test(string &s){
    s="shit";
}
int main(){
    string s{"test"};
    test(s);
    cout<<s<<endl;
}

打印结果:

shit

3.const string&做参数:

首先演示一下如果没有const时,直接传入c语言字符串(即"test")的结果:

void test(string &s){
}
int main(){
    test("test");
}

报错:无法用 “const char [5]” 类型的值初始化 “std::__cxx11::string &” 类型的引用(非常量限定)

加上const后就可以了

void test(const string &s){
	cout<<s<<endl;
}
int main(){
    test("test");
}

打印结果:

test

这里没有报错说明const前缀的应用的一部分原因就是为了方便使用c语言字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值