所以强制输出应该是这样的:
Product Name: Orange
Reference Number: 1123452
Price per unit/pound: 0.99
Stock: 34
但我有这个代码,我做的是我遇到了麻烦,我无法弄清楚出了什么问题:
#include <string>
#include <iostream>
using namespace std;
class Product {
private:
string prodName;
double price;
unsigned refNum, items_remaining;
public:
Product (){
refNum=items_remaining=0; price=0; prodName="";
}
Product ( string prod, unsigned ref, double pri, unsigned stk){
refNum = ref;
items_remaining = stk;
prodName = prod;
price = pri;
}
//Add Accessors
string get_name(string name){
cin>>name;
return prodName;
}
double get_price (double cost){
cin>>cost;
return price;
}
unsigned stock (unsigned items){
cin>>items;
return items_remaining;
}
unsigned sold (unsigned items_remaining, unsigned num_sold){
items_remaining -= num_sold;
return items_remaining;
}
unsigned addToStock (unsigned items_remaining, unsigned stock_add){
stock_add +=items_remaining;
return items_remaining;
}
void info (){
cout<<"Product Name: "<<prodName<<endl;
cout<<"Reference Num: "<<refNum<<endl;
cout<<"Price per unit/pound: "<<price<<endl;
cout<<"Stock: "<<items_remaining<<endl;
}
};
描述:
Product Name: Orange Reference Number: 1123456 Price per unit/pound: 0.99 Stock: 34
答案 0 :(得分:0)
你需要编写一个main()函数,如下所示:
int main()
{
Product a("Orange", 23456, 0.99, 36);
a.sold(4);
a.addToStock(2);
a.info();
}
您需要在Product类中进行更改:
从访问者中删除所有“cin”
变化
unsigned sold(unsigned items_remaining, unsigned num_sold)
到
unsigned sold( unsigned num_sold)
变化
unsigned addToStock(unsigned items_remaining, unsigned stock_add)
到
unsigned addToStock(unsigned stock_add)
变化
stock_add +=items_remaining;
到
items_remaining += stock_add;
您不必将items_remaining作为参数传递给方法。类中的数据可以直接访问同一类的方法。 请参阅:http://www.tutorialspoint.com/cplusplus/cpp_data_encapsulation.htm