此行在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/