You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ISO C++禁止字符串字面量转char*,如何忽略警告运行代码?

问题:C++字符串字面量转char*的编译警告处理

代码片段

class Airport
{
public:
    Airport(char *code, char *name);
private:
    char* airport_code;
    char* airport_name;
};
Airport::Airport(char *code, char *name)
{
    airport_code = new char[20];
    strcpy(airport_code, code);
    airport_name = new char[20];
    strcpy(airport_name, name);
}
int main() {
    
    Airport *lax = new Airport("LAX", "LA");

}

问题描述

运行上述代码时,VS Code提示“ISO C++ forbids converting string to char*”的警告,程序最终以退出代码1终止。已知将参数类型改为const char*可解决警告,但因后续需要通过预定义函数修改类内的相关值,无法采用此方案,询问是否有办法忽略警告以运行代码。

解决方案

1. 直接忽略警告的方法

根据使用的编译器,添加对应编译参数关闭该警告:

  • GCC/Clang编译器:编译时添加 -Wno-write-strings 参数,关闭字符串字面量转换为非const char*的警告。
  • MSVC编译器:编译时添加 /wd4028 参数,关闭形参与实参类型不匹配的警告(对应字符串字面量转char*的场景)。

2. 更安全的代码修正方案(推荐)

你其实无需放弃使用const char*——构造函数只是将传入的字符串内容拷贝到类自己动态分配的airport_code和airport_name内存中,后续要修改的是这些类成员变量,而非传入的参数本身。修改后的代码如下:

class Airport
{
public:
    Airport(const char *code, const char *name); // 参数改为const char*
private:
    char* airport_code;
    char* airport_name;
};
Airport::Airport(const char *code, const char *name)
{
    airport_code = new char[20];
    strcpy(airport_code, code);
    airport_name = new char[20];
    strcpy(airport_name, name);
}

这样既符合C++标准、消除了警告,后续你依然可以正常修改airport_code和airport_name的值(比如通过类的成员函数修改),完全不受参数const的限制。

注意事项

直接忽略警告存在风险:字符串字面量在C++中是只读的,若后续不小心通过原本的char*参数修改传入的字符串字面量,会触发未定义行为(如程序崩溃、内存错误),因此更推荐使用代码修正方案。

内容的提问来源于stack exchange,提问作者Judy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:55:34