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

李丹

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

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

'void CGoods::RegisterGoods(char [],int,float)': cannot convert argument 1 from 'const char [4]' to '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;
}
r3mus n0x

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)

通常,尽管您不应该使用纯char数组在C ++中存储字符串,但是您应该更喜欢使用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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我的代码在空闲状态下运行而不在 vim 中运行?

为什么我的代码无法在Visual Studio Code中运行?

为什么Visual Studio代码无法运行我的代码?

为什么我按下运行后我的代码在程序中什么也不显示?

为什么我的 VS Code 终端没有运行代码?

try块中的代码被忽略,为什么?

我的老师声称此代码块是在O(n)时间运行的……为什么?

为什么我的代码在x64中而不在x32中编译?

std :: map为什么不在我的代码中添加key,values

为什么Symfony 3.3.13源会生成弃用警告(不在我的代码中)?

美丽的汤:为什么不在我的代码中的 for 循环内打印?

为什么 WindowPriceOnDrop() 函数不在我的代码中充当价格存储?

facebook登录-无效的哈希键-为什么它引用不在我的代码中的哈希键?

VS Code中的JavaScript:为什么不能在“ switch”语句中折叠“ case”代码块?

为什么我不能运行代码?

我的代码在 VSCode 中运行但不在 DevC 中运行

为什么在代码块中包装值会将我键入的数字更改为Doubles?

为什么在我的报告程序中根本没有到达给定的代码块?

为什么我的 javaFX 代码在 cmd 上运行良好,但在 Visual Studio Code 中引发错误?

为什么是 sep='.' 不在此代码中工作?

在Android Studio中运行代码时出错

在Visual Studio中运行源代码控制

使用 ”//?” 在 Visual Studio 代码中运行 javascript

节点不在 vs 代码中的集成终端中运行

为什么我在win x86中无法通过VS代码调试我的项目?

为什么在我的代码中需要 ',' 或 ')'?

为什么我的代码中的 if 语句被忽略?

在vert.x中,为什么静态方法在静态代码块之前运行?

为什么此C代码在Codeblock中而不在Visual Studio中进行编译?