1.直接调用API转换
2.隐式类型转换
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; #include <string> /* string和c-style字符串转换 //string 转 char* string str = "itcast"; const char* cstr = str.c_str(); //char* 转 string char* s = "itcast"; string str(s); */ void char2string(string s) { cout << s << endl; } void string2char(char* s) { cout << s << endl; } void test01() { //一、调用接口转换 //string 转char* string s = "abc"; //1.string 转 const char* const char* p = s.c_str(); //2.去掉const char* c = const_cast<char*>(p); cout << "c = " << c << endl; //char* 转 string string s2(c); //c是char* cout << "s2= " << s2 << endl; //二、隐式转换 //1.char转string char2string(c); //隐式类型转换为 string //2.string 转char string2char(s2); //error } int main() { test01(); system("Pause"); return 0; }
char*可以隐式转换成string,而string不能隐式转换成char*