char*和string的赋值

char*可以直接赋值给string。

#include 

using namespace std;

int main()
{
   char * hello = "Hello world";
   string hellostr = hello;
   cout << hellostr << "\t" << hello << endl; 
   
   return 0;
}
$g++ -o main *.cpp
main.cpp: In function ‘int main()’:
main.cpp: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 强制类型转换。

你可能感兴趣的:(c和c++程序设计,c++/visual,studio常见问题,蓝桥杯,c++,职场和发展)