char*可以直接赋值给string。
#include <iostream>
using namespace std;
int main()
{
char * hello = "Hello world";
string hellostr = hello;
cout << hellostr << "\t" << hello << endl;
return 0;
}
$g++ -o main *.cpp
: In function ‘int main()’:
:7:19: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
char * hello = "Hello world";
^~~~~~~~~~~~~
$main
Hello world Hello world
const char*不可以直接赋值给char*。因为前者是指向常量的指针,表示指向的字符串不可改变;后者则可以改变字符串内容。如果可以赋值,意味着const的被改变。解决的办法:
1 strcpy函数
2 强制类型转换。