我試圖在三個數組中創建一個主對象。當我運行它時,它會顯示所需的輸出,但它會給出錯誤,並且之後的任何代碼都不會運行。 「Grocery.exe中0x775FC41F未處理的異常:Microsoft C++異常:內存位置0x0036E590處的std :: bad_alloc」。使用類和構造函數並創建一個數組大小爲3的對象名稱
class GroceryItem {
public:
GroceryItem();//default constructor
GroceryItem(string, double, int, int); // four argument constructor
void set_item_name(string); // Assigns a value to the data memeber item_name
void set_item_price(double); //Assigns a value to the data member item_price
void set_qty_on_hand(int);// Assigns a value to the data member quantity_on_hand.
void set_qty_purchased(int); // Sets qty_purchased to zero before a customer begins shopping.
string get_item_name(); // Returns the value of the data memebr item_name.
double get_item_price(); // Returns the value of the data member item_price
int get_qty_on_hand(); // Returns the value of the data member quantity_on_hand.
int get_qty_purchased(); // Retruns the value of the data memebr qty_purchased.
private:
string item_name;
double item_price;
int quantity_on_hand;
int quantity_purchased;
};
GroceryItem::GroceryItem(string name, double price, int hand, int purchased){
set_item_name(name);
set_item_price(price);
set_qty_on_hand(hand);
set_qty_purchased(purchased);
}
void GroceryItem::set_item_name(string name){
item_name = name;
}
string GroceryItem::get_item_name(){
return item_name;
}
void GroceryItem::set_item_price(double price){
item_price = price;
}
double GroceryItem::get_item_price(){
return item_price;
}
void GroceryItem::set_qty_on_hand(int hand){
quantity_on_hand = hand;
}
int GroceryItem::get_qty_on_hand(){
return quantity_on_hand;
}
void GroceryItem::set_qty_purchased(int purchased){
if (purchased > 0)
quantity_purchased = purchased;
if (purchased <= 0)
{
quantity_purchased = 0;
cout <<"\n cart cannot be negative, it will be set to 0. \n";
}
}
int GroceryItem::get_qty_purchased(){
return quantity_purchased;
}
int main(){
int input;
cout <<"Welcome to KMART\n" << "\nHappy Shopping" << endl;
GroceryItem Kmart("Hello", 1234, 1234, 1);
GroceryItem Kmart2("My", 1234, 1234, 1);
GroceryItem Kmart3[SIZE] = {
{ "John", 1234, 1234, 0 },
{ "Mary", 1234, 1234, 0 },
{ "Kevin", 1234, 1234, 0 }
};
//Kmart("jjj", 12, 123, 1);
for (int i = 0; i < 10; i++){
cout << Kmart3[i].get_item_name() << "\t" << Kmart3[i].get_item_price() << "\t" << Kmart3[i].get_qty_on_hand() << "\t" << Kmart3[i].get_qty_purchased() << endl;
}
cout << "This is fromt eh four argument constructor" << endl;
cout<<Kmart.get_item_name()<<"\t"<<Kmart.get_item_price()<<"\t"<<Kmart.get_qty_on_hand()<<"\t"<<Kmart.get_qty_purchased()<<endl;
cout << Kmart2.get_item_name() << "\t" << Kmart2.get_item_price() << "\t" << Kmart2.get_qty_on_hand() << "\t" << Kmart2.get_qty_purchased() << endl;
}
錯誤來自Kmart3輸出。 – 2014-11-23 06:01:05