c++ - 为什么我的代码在代码块下运行而不是在 VS Studio 中运行

标签 c++

此行在VS Studio下无法通过,但在CodeBlocks下运行。

cg1.RegisterGoods("c++", 23, 32);

“void CGoods::RegisterGoods(char [],int,float)”:无法将参数 1 从“const char [4]”转换为“char []”

像这样:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <cstring>
using namespace std;

class CGoods
{
private:
    char    Name[21];
    int Amount;
    float   Price;
    float   Total_value;

public:
    void  RegisterGoods(char name[], int amount, float price)
    {
        strcpy(Name,name);
        Amount = amount;
        Price = price;
    }
    void  CountTotal(void)
    {
        Total_value = Price * Amount;
    }
    void  GetName(char name[])
    {
        strcpy(name,Name);
    }
    int GetMount(void)
    {
        return Amount;
    }

    float GetPrice(void)
    {
        return Price;
    }
    float GetTotal(void)
    {
        return Total_value;
    }
};

int  main() {
    CGoods cg1;
    cg1.RegisterGoods("c++", 23, 32);
    cout<<cg1.GetPrice()<<endl;
    cout<<cg1.GetMount();
    return 0;
}

最佳答案

char name[] 作为函数参数等同于 char *name 而您的字符串文字具有类型 const char [4]它只能(安全地)转换为 const char *,因此您必须像这样更改参数:

void RegisterGoods(const char *name, int amount, float price)

这里:

 // Renamed to SetName given that it's what this function actually does
void SetName(const char *name)

一般来说,尽管在 C++ 中您不应该使用普通的 char 数组来存储字符串,但您应该更喜欢使用 std::string:

std::string Name;
...
void SetName(std::string name)
{
    // take advantage of move semantics to avoid redundant copying
    // if you are using C++11 and beyond
    Name = std::move(name);
}

关于c++ - 为什么我的代码在代码块下运行而不是在 VS Studio 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470555/

相关文章:

c++ - 什么时候可以在#include 指令中省略文件扩展名?

c++ - 函数调用后字符串发生变化

c++ - 创建字符数组避免缩小

c++ - 为什么我的 for 循环在检查 vector 是否排序时无法正常工作?

c++ - BPP 颜色变化 SDL

c++ - 来自 Windows 原始输入的水平鼠标滚轮消息

c++ - 如何确定 MSADO 命令参数的大小

c++ - 类中成员声明的重新排序规则

c++ - 如何让 boost json 使用正确的数据类型

c++ - 使用 std::map 查找数据中的重复项及其性能问题。我可以预分配吗?