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语言字符串。