char*和string的赋值

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
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 强制类型转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值