C ++-字符*与字符串* [英] C++ - char* vs. string*

查看:134
本文介绍了C ++-字符*与字符串*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个指向字符串变量array of chars的指针,键入之间是否有区别:

If I have a pointer that points to a string variable array of chars, is there a difference between typing:

char *name = "name";

然后

string name = "name";

推荐答案

是的,有所不同.主要是因为您可以修改字符串,但是不能修改第一个版本-但是C ++编译器甚至不会警告您,如果尝试这样做是禁止的.

Yes, there’s a difference. Mainly because you can modify your string but you cannot modify your first version – but the C++ compiler won’t even warn you that this is forbidden if you try.

所以请始终使用第二个版本.

So always use the second version.

如果无论出于何种原因需要使用char指针,请将其设置为const:

If you need to use a char pointer for whatever reason, make it const:

char const* str = "name";

现在,如果您尝试修改str的内容,编译器将禁止这样做(正确).您还应该将编译器的警告级别提高一个等级:然后它将警告您的第一个代码(即char* str = "name")合法但已弃用.

Now, if you try to modify the contents of str, the compiler will forbid this (correctly). You should also push the warning level of your compiler up a notch: then it will warn that your first code (i.e. char* str = "name") is legal but deprecated.

这篇关于C ++-字符*与字符串*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆