我有三个C ++类,InventoryItem,SalesPerson和Transaction。我使用组合在Transaction中使用InventoryItem和SalesPerson类。我想使用用户输入而不是仅仅在构造函数中传递值,但我无法做到这一点。任何帮助将受到高度赞赏。以下是我的C ++文件。
#include<iostream>
#include<string>
using namespace std;
class InventoryItem {
private:
int stockNum; double price;
public:
InventoryItem(int, double);
void display(); };
InventoryItem::InventoryItem(int stkNum, double pr) {
stockNum = stkNum;
price = pr;
}
void InventoryItem::display() {
cout << "Item #" << stockNum << " costs $" << price << endl;
}
//SalesPerson class
class Salesperson {
private:
int idNum;
string name; public:
Salesperson(int, string); void display();
};
Salesperson::Salesperson(int id, string lastName) {
idNum = id;
name = lastName;
}
void Salesperson::display() {
cout << "Salesperson #" << idNum << " " << name << endl;
}
//Transaction(main class)
class Transaction {
private:
int transNum;
InventoryItem itemSold;
Salesperson seller;
public:
Transaction(int, int, double, int, string);
void display();
};
Transaction::Transaction(int num, int item, double pr,
int salesId, string name) : itemSold(item, pr),
seller(salesId, name) {
transNum = num;
}
void Transaction::display() {
cout << "Data for transaction #" << transNum << endl; itemSold.display();
seller.display();
}
int main() {
Transaction aSale(247, 782, 44.77, 512, "Richardson"); aSale.display();
return 0;
}
答案 0 :(得分:0)
我发布这个作为答案而不是评论,因为我的手机上没有反引号。所以你想做一些像
这样的事情int main()
{
int x, y, z;
double f;
string name;
cin >> x >> y >> f >> z >> name;
Transaction(x, y, f, z, name);
return 0;
}
当然,您可以将cin
行划分为每个变量cin
和cout
指示用户必须输入的内容。这看起来像这样
int main()
{
int x, y, z;
double f;
string name;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
cout << "Enter f: ";
cin >> f;
cout << "Enter z: ";
cin >> z;
cout << "Enter name: ";
cin >> name;
Transaction(x, y, f, z, name);
return 0;
}
将cout
行中的字符串替换为您想要提示用户的字符串。