简体   繁体   English

可以在C ++中将参数从'const char []'转换为'char *'吗?

[英]Is possible to convert argument from 'const char []' to 'char *' in C++?

Definition of method is: 方法的定义是:

void setArgument(char *);

And i call that method with this code: 我用以下代码调用该方法:

setArgument("argument");

But my VisualStudio compiler gets me the next error: 但是我的VisualStudio编译器让我遇到下一个错误:

cannot convert argument 1 from 'const char [10]' to 'char *' 无法将参数1从'const char [10]'转换为'char *'

Is it possible to send arguments like this or I must change arguments type in the method? 是否可以发送这样的参数,或者我必须在方法中更改参数类型? Also, VS show me next note in output: note: Conversion from string literal loses const qualifier (see /Zc:strictStrings) 另外,VS在输出中向我显示下一个注释:注意:从字符串文字转换会丢失const限定符(请参见/ Zc:strictStrings)

The problem is that string literals are arrays of constant characters. 问题在于字符串文字是常量字符的数组。

While the array could easily decay to a pointer to its first element, the type of that pointer is const char * . 尽管数组可以轻易地衰减为指向其第一个元素的指针,但该指针的类型为const char * Which needs to be the type of the argument for your functions. 哪个必须是函数的参数类型。

And if you need to modify the string you pass, then you should create your own non-constant array: 而且,如果您需要修改传递的字符串,则应该创建自己的非常数数组:

char argument[] = "argument";
setArgument(argument);

Of course, since you're programming in C++ you should stop using char pointers and arrays and instead use std::string . 当然,由于您使用C ++进行编程,因此应停止使用char指针和数组,而应使用std::string

It's possible, just if you really need the argument to be mutable ( char* and not char const* ), you need to allocate a new storage in the mutable memory and clone the contents of the constant memory to there, if that fits into your definition of "convert". 有可能,就算您真的需要参数是可变的( char*而不是char const* ),也需要在可变内存中分配一个新存储,并在该内存中克隆常量内存的内容(如果适合) “转换”的定义。

auto const len = strlen(input);
auto const buf = std::unique_ptr<char[]>(new char[len + 1]);
memcpy(buf, input, len + 1);

If you actually need char const* and if you are C++17 or later, you can possibly change the signature to setArgument(std::string_view arg) , making it misuse-proof. 如果您实际上需要char const* ,并且您使用的是C++17或更高版本,则可以将签名更改为setArgument(std::string_view arg) ,以setArgument(std::string_view arg)滥用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM