【发布时间】:2024-01-13 12:50:01
【问题描述】:
我有 this code 按预期工作:
#define MAX_PARAM_NAME_LEN 32
const char* GetName()
{
return "Test text";
}
int main()
{
char name[MAX_PARAM_NAME_LEN];
strcpy(name, GetName());
cout << "result: " << name << endl;
}
如果我想将结果存储到 char *(因为我使用的框架中的某些函数仅使用 char * 作为输入)而不使用 strcpy(为了代码的实用性和可读性,和学习),我该怎么办?保持const,这很好用:
const char* name;
name = GetName();
但我还有const。
尝试只使用char*:
char* name;
name = GetName();
我收到invalid conversion from 'const char*' to 'char*'。这种转换的最佳习惯是什么?
【问题讨论】:
-
你想做什么?如果您不想更改字符串,则第一个成语为您服务,并且不会使用额外的内存;如果要更改字符串,则需要将其内容复制到其他位置(因此您需要 strcpy 或类似的)。
标签: c++ char constants type-conversion