char *、const char*和string三者转换

const char* 和string转换

  1. cosnt char *转换为string,直接复制即可。
    荔汁:
    const char*  temp = "rookie"
    string s = temp;
  1. string转换为const char* ,利用c_str()
    荔汁:
    string s = "rookie"
    const char *temp = s.c_str();

char和const char之间的转换

  1. const char转化为char,利用const_cast>去常转换*
    荔汁:

    const char* temp = "rookie"
    char *p = const_cast(tmp);
    
    
  2. char*转化为const char,直接赋值即可。**

    char *p = "rookie"
    const char *tmp = p;
    

3.char*和string之间的转换

a. char* 转化为string,直接复制节课
荔汁:

char *p = "rookie"
string str = p;

b.string转化为char*,走两步,显示string->const char **,然后是const char*->char *
荔汁:

string str = "rookie"
char *p = const_cast(str.c_str());

你可能感兴趣的:(c++)