c++ 我正在尝试打印这3个给定对象,但无法打印!它显示:从“const char*”到“int”的转换无效[-fpermissive] [已关闭]

scyqe7ek  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(136)

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
昨天关门了。
Improve this question

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;
}

请检查我是否还没有声明一些东西。我看不到转换发生,它在哪里?我已经创建了一个类的创建3对象(音频设备设备1,2,3分别)。我做了同样的程序,但它需要输入(这是通过使用cin〈〈)。但它是一个简单的程序相比,动态输入程序。我会喜欢它,如果有人能帮我修复这个代码。

mnemlml8

mnemlml81#

Device1.year = "2021";
Device1.cost = "11999";

应该是

Device1.year = 2021;
Device1.cost = 11999;

(其他器械的年/成本类似)。
或者,您可以执行以下操作:

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

std::ostream& operator << (std::ostream& os, const AudioDevice& device)
{
    return os << device.brand
              << " " << device.model
              << " " << device.year
              << " " << device.cost;
}

int main()
{
    AudioDevice devices[] = {
        { "Apple", "AirPods Pro", 2021, 11999},
        { "boAt", "Bassheads", 2021, 3999},
        { "Marshall", "Emberton", 2020, 15499}
    };
    for (const auto& device : devices) {
        std::cout << device << "\n" << std::endl;
    }
}

Demo

相关问题