1、向string类型传递char *
#include <string>
#include <iostream>
using namespace std;
void test(string str)
{
cout << str.size() << endl;
}
int main()
{
//char *line = "hello";
char line[] = "hello";
test(line);
getchar();
}
这样是可以的,这样在test函数中会生成一个临时变量,通过c风格字符串初始化,string str(line);
2、向string &类型传递char *类型
#include <string>
#include <iostream>
using namespace std;
void test(string &str)
{
cout << str.size() << endl;
}
int main()
{
//char *line = "hello";
char line[] = "hello";
test(line);
getchar();
}
这样不可以
3、向const string &传递char *类型
#include <string>
#include <iostream>
using namespace std;
void test(const string &str)
{
cout << str.size() << endl;
}
int main()
{
//char *line = "hello";
char line[] = "hello";
test(line);
getchar();
}
这样也是可以的