我有作業使用動態分配的內存。我的教授給了我一些指示。使用它們,我編碼了下面的代碼。隨機時間出現錯誤。在執行復制之前有時出現錯誤。有時它會複製一個對象而不會複製下一個對象。我不明白我做錯了什麼。動態分配內存,複製構造函數中的錯誤
默認的構造
GroceryItem::GroceryItem()
{
item_name = new char[strlen("") + 1];
strcpy(item_name, "");
item_price = 0;
qty_on_hand = 0;
qty_purchased = 0;
};
功能下面是我用它來複制兩個對象的拷貝構造函數:
GroceryItem::GroceryItem(const GroceryItem& Grocery_in)
{
item_name = new char[strlen(Grocery_in.item_name) + 1];
strcpy(item_name, Grocery_in.item_name);
item_price = Grocery_in.item_price;
qty_on_hand = Grocery_in.qty_on_hand;
qty_purchased = Grocery_in.qty_purchased;
}
;
下面
被分配新建分配FY opperator
GroceryItem& GroceryItem::operator=(GroceryItem& copy_item)
{
if (this == ©_item)
return *this;
else
{
delete[] item_name;
item_name = new char[strlen(copy_item.item_name)+1];
strcpy(item_name, copy_item.item_name);
item_price = copy_item.item_price;
qty_on_hand = copy_item.qty_on_hand;
qty_purchased = copy_item.qty_purchased;
return *this ; // They are the same
}
}
從函數調用如下當我嘗試複製到temp2:
void sort_items(GroceryItem ini_customer_GroceryItem[], int number)
{
int j = 0, k = 0;
GroceryItem temp2;
for (j = 0; j < number - 1; j++) // n-1 passes
{
for (k = number - 1; j < k; k--) // each pass runs one fewer than the preceding one
{
if (ini_customer_GroceryItem[k - 1] > ini_customer_GroceryItem[k])
{
temp2 = ini_customer_GroceryItem[k - 1];
ini_customer_GroceryItem[k - 1] = ini_customer_GroceryItem[k];
ini_customer_GroceryItem[k] = temp2;
}
}
}
}
以下是錯誤
你的教授是在幫你幫倒忙通過指示你寫陳舊的C代碼strcpy()和strlen(),而不是花時間教你真正的C++代碼,比如'std :: string',它不需要任何這些廢話。爲了成爲一名熟練的C++開發人員,您沒有被教授必要的技能。附:我看到複製構造函數沒有錯。內存損壞很可能發生在其他地方。僅僅因爲你的代碼在一個特定的地方崩潰了,也就是拷貝構造函數,並不意味着它就是錯誤所在。請發佈[mcve]。 –
這不是一個拷貝構造函數,它是一個賦值操作符,它應該通過const引用來引用它的參數。「 –
」下面的函數是拷貝構造函數「 - 實際上它是賦值操作符。你的拷貝構造函數在哪裏? –