2017-03-03 64 views
-3
class Bag 
{ 
protected: 
    Item** myItems; 
    int numItems; 
public: 
Bag(); 
Bag(Item** items, int numberOfItems); 
Bag(const Bag& other); 
/** 
Bag instance destructor 
*/ 
virtual ~Bag(); 
/** 
Defines the = operation to assign an Bag 
*/ 
void operator= (const Bag& m); 
/** 
Defines the << operation to display an Bag 
*/ 
friend ostream& operator<< (ostream& s, Bag& m); 
/** 
Prints out Bag instance 
*/ 
virtual void display(ostream& s); 
/** 
Add an item to the bag 
*/ 
void addItem(int pos, Item* newItemPtr); 
/** 
deletes an item in the bag 
*/ 
void deleteItem(int pos); 
//---------------------------------------------------------- 
Bag::Bag() 
{ 
    myItems = NULL; 
    numItems = NULL; 
} 
//---------------------------------------------------------- 
Bag::Bag(Item** items, int numOfItems) 
{ 
    myItems = new Item*[numOfItems]; 
    numItems = numOfItems; 
} 
//---------------------------------------------------------- 
Bag::Bag(const Bag& other) 
{ 
    myItems = other.myItems; 
    numItems = other.numItems; 
} 
//---------------------------------------------------------- 
Bag::~Bag() 
{ 
    cout << "BAG ELIMINATED" << endl; 
} 
//---------------------------------------------------------- 
void operator= (const Bag& m) 
{ 
    myItems = m.myItems; 
    numItems = m.numItems; 
} 
//---------------------------------------------------------- 
friend ostream& operator<< (ostream& s, Bag& m) 
{ 

} 
//---------------------------------------------------------- 
void display(ostream& s) 
{ 

} 
//---------------------------------------------------------- 
void addItem(int pos, Item* newItemPtr) 
{ 
    Item** temp = myItems; 
    myItems = new Item*[numItems + 1]; 
     for (int i = 0; i < numItems; i++) 
     { 
      if (i < pos) 
      { 
       myItems[i] = temp[i]; 
       temp[i] = NULL; 
      } 
      else if (i == pos) 
      { 
       myItems[i] = newItemPtr; 
      } 

      else if (i > pos) 
      { 
       myItems[i] = temp[i-1]; 
       temp[i-1] = NULL; 
      } 
     } 
    delete[] temp; 
    numItems++; 
} 
//---------------------------------------------------------- 
void deleteItem(int pos) 
{ 
    Item** temp = myItems; 
    myItems = new Item*[numItems-1]; 
    for (int i = 0; i < numItems; i++) 
    { 
     if (i < pos) 
     { 
      myItems[i] = temp[i]; 
      temp[i] = NULL; 
     } 
     else if (i == pos) 
     { 
      temp[i] = NULL; 
     } 

     else if (i > pos) 
     { 
      myItems[i-1] = temp[i]; 
      temp[i] = NULL; 
     } 
    } 
    delete[] temp; 
    numItems--; 
} 
}; 

因此,我正在嘗試定義每種方法的行中出現錯誤,如「Bag :: Bag()」。我想知道爲什麼它給了我這些「成員函數已經定義或聲明」的錯誤,因爲我的其他類沒有這個錯誤。C++類錯誤

+1

_「我得到的錯誤」_請具體說明錯誤,並在您的問題中發佈逐字錯誤文本。 –

回答

0

您已經在類聲明中聲明瞭兩次構造函數。 一旦在班級申報的開始,然後再使用Bag :: Bag。

也許你的意圖是將定義從聲明中分離出來,但在這種情況下,你必須在單獨的文件中定義它們,或者至少在類聲明的括號之後定義它們。

class X{ 
    X(); 
}; 

X::X(){ 
}