你现在的buy函数没有返回值,没法体现能买多少产品和剩余的钱。整体代码及测试代码如下(如有帮助,请采纳一下,谢谢。):
#include <stdio.h>
#include <cstring>
class product
{
private:
char* name; //产品名
int price; //单价
int quantity;//数量
public:
product(char* n,int p ,int q);
~product();
void buy(int money, int &nmb,int &lm); //购买产品
int get(); //显示剩余产品数量,原来的返回类型void是错误的
};
product::product(char* n,int p ,int q)
{
name = 0;
if(n)
{
int len = strlen(n);
name = new char[len+1];
memset(name,0,len+1);
memcpy(name,n,len);
}
price = p;
quantity = q;
}
product::~product()
{
if(name)
{
delete[] name;
name = 0;
}
}
//nmb是可以买的数量,lm是剩余的钱
void product::buy(int money, int &nmb,int &lm)
{
nmb = money / price;
if(nmb > quantity)
nmb = quantity;
quantity = quantity - nmb; //计算本次购买后剩余的数量
lm = money - nmb * price;
}
int product::get()
{
return quantity;
}
//测试代码
void main()
{
product protest("abc",12,20);
int nmb = 0;
int ll = 0;
protest.buy(110,nmb,ll);
printf("可买产品数量:%d,剩余钱数:%d,产品剩余数量:%d",nmb,ll,protest.get());
getchar();
getchar();
}
以上,望采纳,谢谢。