该行在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;
}
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] 删除。
我来说两句