C++ 字符串引用传递:提高效率和实现直接操作
在 C++ 中,字符串可以用字符数组或者字符串类来表示。如果想要通过引用传递字符串,可以使用字符数组或者字符串类的引用类型作为函数参数。
字符数组的引用传递示例:
#include <iostream>
using namespace std;
void printString(char (&str)[10]) { // 字符数组的引用类型
cout << str << endl;
}
int main() {
char str[] = 'hello';
printString(str);
return 0;
}
字符串类的引用传递示例:
#include <iostream>
#include <string>
using namespace std;
void printString(string& str) { // 字符串类的引用类型
cout << str << endl;
}
int main() {
string str = 'hello';
printString(str);
return 0;
}
通过引用传递字符串可以避免对字符串进行拷贝,提高程序执行效率。同时,引用传递还可以修改原字符串,实现对字符串的直接操作。
原文地址: https://www.cveoy.top/t/topic/ne7W 著作权归作者所有。请勿转载和采集!