我有三個C++類,InventoryItem,SalesPerson和Transaction。我正在使用組合在Transaction中使用InventoryItem和SalesPerson類。我想使用用戶輸入,而不是在構造函數中傳遞值,但我無法做到這一點。任何幫助將不勝感激。以下是我的C++文件。如何在C++中使用組合作爲用戶輸入「cin」
#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;
}
將參數傳遞給構造函數沒有任何問題。這是你*應該*做的方式。用戶輸入應分開處理。這使得代碼可以在輸入類型改變時重用和測試(即用戶輸入vs文件vs模擬)。 –