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

C++代码报错:const char*转int无效,请求代码修复帮助

编译错误修复:invalid conversion from 'const char*' to 'int'

错误原因

你的AudioDevice类中,year和cost成员被定义为int(整数)类型,但在初始化对象时,你给这两个成员赋值了带双引号的字符串字面量(例如"2021"、"11999")。C++不支持这种隐式的字符串到整数的转换,因此触发编译错误。
另外你的代码还遗漏了必要的头文件,未声明std命名空间的情况下,string和cout会无法识别,这也是潜在问题。

修复后的完整代码

#include <iostream>
#include <string>

using namespace std;

class AudioDevice {
    public:
        string brand;
        string model;
        int year;
        int cost;
};

int main()
{
    AudioDevice Device1;
    Device1.brand = "Apple";
    Device1.model = "AirPods Pro";
    Device1.year = 2021;  // 去掉双引号,用整数赋值
    Device1.cost = 11999;

    AudioDevice Device2;
    Device2.brand = "boAt";
    Device2.model = "Bassheads";
    Device2.year = 2021;
    Device2.cost = 3999;

    AudioDevice Device3;
    Device3.brand = "Marshall";
    Device3.model = "Emberton";
    Device3.year = 2020;
    Device3.cost = 15499;

    cout << Device1.brand << " " << Device1.model << " " << Device1.year << " " << Device1.cost << "\n" << endl;
    
    cout << Device2.brand << " " << Device2.model << " " << Device2.year << " " << Device2.cost << "\n" << endl;
    
    cout << Device3.brand << " " << Device3.model << " " << Device3.year << " " << Device3.cost << "\n" << endl; 

    return 0;
}

关键修改点

  • 把所有赋值给year和cost的带双引号字符串改为整数(例如"2021" → 2021)
  • 添加了必要的头文件<iostream>(用于cout输出)和<string>(用于string类型)
  • 添加using namespace std;,避免每次都写std::前缀(若不想使用该命名空间,也可将string改为std::string、cout改为std::cout)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:17:12