2015-02-18 23 views
1

我似乎正在修復某些內容,因爲當我運行我的程序時我得到的輸出: 無法禁用您的Grocery的信息,因爲目前沒有有效的信息 無論我輸入什麼雜貨店ID和名稱。 下面是我的類定義:重載的等於不能撥打電話

3 #include <iostream> 
    4 using namespace std; 
    5 Grocery::Grocery(){ 
    6   id =0; 
    7   name=nullptr; 
    8 } 
    9 Grocery::Grocery(char* ProductName,int Productid){ 
10   if (id < 0 || name == nullptr) { 
11     id =0; 
12     name=nullptr; 
13   } 
14   else{ 
15     name=new char[strlen(ProductName)+1]; 
16     strcpy(name,ProductName); 
17     id=Productid; 
18   } 
19 } 
20 Grocery::Grocery(Grocery &src){ 
21     id=src.id; 
22     if (src.name==nullptr) { 
23       name = new char[strlen(src.name+1)]; 
24       strcpy(name,src.name); 
25     } 
26     else 
27       name=nullptr; 
28 } 
29 Grocery::~Grocery(){ 
30   delete [] name; 
31   name = nullptr; 
32 } 
33 void Grocery::display() const{ 
34   if (id == 0 && name == nullptr) 
35     cout<<"Unable to disable your Grocery's information as there is no valid information at this time"<<endl; 
36   else 
37     cout<<"The Grocery's id is "<< id <<" and the name of the item is "<< name; 
38 } 
39 bool Grocery::isGreaterThan(const Grocery &src)const{ 
40   if(id>src.id) 
41     return true; 
42   else 
43     return false; 
44 } 
45 Grocery& Grocery::Grocery::operator=(const Grocery& src){ 
46   if (this !=&src) { 
47     id=src.id; 
48     delete [] name; 
49   } 
50   if (src.name != nullptr) { 
51     name = new char[strlen(src.name) + 1]; 
52     strcpy(name,src.name); 
53   } 
54   else 
55     name = nullptr; 
56   return *this; 
57 } 

我假設我固定的東西很簡單,我的類定義,但任何幫助將是很好。

+1

它應該是'Grocery&Grocery :: operator =(const Grocery&src)' – 2015-02-18 00:25:04

+0

@PaulRooney它很*很古怪,但仍然有效。 – hvd 2015-02-18 00:28:11

+0

請編輯您的問題以提供'Grocery'類的聲明。 – 2015-02-18 00:31:14

回答

0
Grocery::Grocery(char* ProductName,int Productid){ 
    if (id < 0 || name == nullptr) { 

這似乎是你的大問題。當您應該檢查ProductNameProductid構造函數參數時,您正在檢查尚未初始化的idname類成員。

您可能會得到id的半隨機垃圾值,並且這些垃圾值可能最終爲負數。

+0

謝謝HVD,我以爲我錯過了一些簡單的:)。 – 2015-02-18 02:52:02