BZ易风

导航

 

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*

 

posted on 2021-08-26 13:40  BZ易风  阅读(72)  评论(0编辑  收藏  举报