下面是代碼的一部分:C++程序執行對象功能時崩潰
class Inventory {
public:
void PrintInventory();
void AddItemToInventory();
void UpdateItemQtyInInventory();
void RemoveItemFromInventory();
private:
vector<Item*> inventory;
};
void Inventory::PrintInventory() {
unsigned int i = 0;
if (inventory.size() == 0) {
cout << "No items to print." << endl;
} else {
for (i=0; i < inventory.size(); ++i) {
cout << i << " - ";
inventory.at(i)->Print();
}
}
return;
}
void Inventory::AddItemToInventory() {
string usrInptName = "";
string usrInptQntyStr = "";
string usrInptPriceStr = "";
string usrInptOptn = "default";
istringstream inSS;
int usrInptQnty = 0;
int usrInptPrice = 0;
string usrInptOther = "";
bool valid = false;
while (valid == false) {
cout << "Enter (b)ook or (p)roduce: ";
getline(cin, usrInptOptn);
if (usrInptOptn.size() == 0) {
continue;
} else if (usrInptOptn.at(0) == 'p') {
Produce* prdct;
cout << "Enter name of new produce: ";
getline(cin, usrInptName);
cout << "Enter the price per item: $";
getline(cin, usrInptPriceStr);
inSS.str(usrInptPriceStr);
inSS >> usrInptPrice;
inSS.clear();
cout << "Enter quantity: ";
getline(cin, usrInptQntyStr);
inSS.str(usrInptQntyStr);
inSS >> usrInptQnty;
inSS.clear();
cout << "Enter expiration date: ";
getline(cin, usrInptOther);
prdct = new Produce;
prdct->SetName(usrInptName);
prdct->SetPrice(usrInptPrice);
prdct->SetQuantity(usrInptQnty);
prdct->SetExpiration(usrInptOther);
inventory.push_back(prdct);
valid = true;
} else if (usrInptOptn.at(0) == 'b') {
Book* prdct;
cout << "Enter name of new book: ";
getline(cin, usrInptName);
cout << "Enter the price per item: $";
getline(cin, usrInptPriceStr);
inSS.str(usrInptPriceStr);
inSS >> usrInptPrice;
inSS.clear();
cout << "Enter quantity: ";
getline(cin, usrInptQntyStr);
inSS.str(usrInptQntyStr);
inSS >> usrInptQnty;
inSS.clear();
cout << "Enter Author: ";
getline(cin, usrInptOther);
prdct = new Book;
prdct->SetName(usrInptName);
prdct->SetPrice(usrInptPrice);
prdct->SetQuantity(usrInptQnty);
prdct->SetAuthor(usrInptOther);
inventory.push_back(prdct);
valid = true;
} else {
cout << "Invalid choice\n";
}
}
return;
}
Inventory* inventory;
int main() {
string usrInptOptn = "default";
while (true) {
// Get user choice
cout << "\nEnter (p)rint, (a)dd, (u)pdate, (r)emove, or (q)uit: ";
getline(cin, usrInptOptn);
// Process user choice
if (usrInptOptn.size() == 0) {
continue;
} else if (usrInptOptn.at(0) == 'p') {
inventory->PrintInventory();
} else if (usrInptOptn.at(0) == 'a') {
inventory->AddItemToInventory();
} else if (usrInptOptn.at(0) == 'u') {
inventory->UpdateItemQtyInInventory();
} else if (usrInptOptn.at(0) == 'r') {
inventory->RemoveItemFromInventory();
} else if (usrInptOptn.at(0) == 'q') {
cout << "\nGood bye." << endl;
break;
}
}
return 0;
}
當它正在運行的功能的程序崩潰。我沒有絲毫的想法。 AddItemtoIventory函數在程序崩潰之前全部運行,而另一個和其他程序崩潰。
如何使用調試器來遍歷代碼並詢問更具體的問題? – 2014-11-21 18:28:38
庫存*庫存;'< - 這。這是未初始化和壞。你在這裏不需要全球化。 2.你不需要一個指針。 – crashmstr 2014-11-21 18:28:38
如果你可以發佈與這個問題有關的崩潰日誌將是有幫助的 – 2014-11-21 18:28:46