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
string&做参数:
void test(string &s){
s="shit";
}
int main(){
string s{"test"};
test(s);
cout<<s<<endl;
}
打印结果:shit
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
本文链接:https://blog.csdn.net/weixin_44727250/article/details/103976227