Hello, I am trying to create a container/iterator.
But I am stuck.
My Add Function is wrong, I'm not using pointers correctly.
But here is the thing:
I need to make this ex without the functions : Next(), Head(), Tail() returning a pointer.
Please can someone help me?
Code:
#include <iostream>
using namespace std;
typedef enum{YELLOW, RED, GREEN, BLUE} LegoPieceColor;
class LegoPiece{
private:
LegoPieceColor m_color;
int m_height, m_width, m_length;
public:
LegoPiece(LegoPieceColor color, int height, int width, int length)
: m_color(color),m_height(height),m_width(width),m_length(length){}
virtual ~LegoPiece(){}
friend std::ostream& operator<<(std::ostream& ostr, const LegoPiece& piece){
ostr << piece.m_color << piece.m_height << piece.m_width << piece.m_length;
return ostr;
}
LegoPiece(const LegoPiece &other)
{
cout << "sup\n";
m_height = other.m_height;
m_length = other.m_length;
m_width = other.m_width;
m_color = other.m_color;
}
};
class Box{
public:
//Iterator
class Iterator{
friend class Box;
LegoPiece *m_pPiece;
Iterator *m_pNext;
public:
Iterator(LegoPiece* piece = 0, Iterator *next = 0){
m_pPiece = piece;
m_pNext = next;
}
Iterator(const Iterator &it){
this->m_pPiece = it.m_pPiece;
this->m_pNext = it.m_pNext;
}
virtual ~Iterator(){
//delete m_pPiece;
//delete m_pNext;
}
Iterator Next()const{
return *m_pNext;
}
LegoPiece* GetLegePiece()const{
return m_pPiece;
}
bool operator==(const Iterator &it){
if (it.m_pPiece == this->m_pPiece)
return true;
else
return false;
}
bool operator!=(const Iterator &it){
if (it.m_pPiece == this->m_pPiece)
return false;
else
return true;
}
};
private:
Iterator *m_pHead, *m_pTail;
char *m_name;
public:
Box(const char* name = 0){
m_name = new char[strlen(name) + 1];
strcpy(m_name, name);
m_pHead = NULL;
m_pTail = new Iterator();
}
virtual ~Box(){
// Delete everything
}
Iterator Head()const{
return *m_pHead;
}
Iterator Tail()const{
return *m_pTail;
}
/* friend std::ostream& operator<<(std::ostream& ostr, const Box& b){
Iterator it;
for(it =b.Head(); it.Next() != b.Tail(); it = it.Next())
{
cout << "sdf\n";
ostr <<*it.GetLegePiece() << endl;
}
return ostr;
}
*/
void Add(LegoPiece *piece){
if(m_pHead == NULL){
m_pHead = new Iterator(piece, m_pTail);
} else {
Iterator it;
for(it = Head(); it.Next() != Tail(); it = it.Next());
it.m_pNext = new Iterator(piece, m_pTail);
}
}
};
int main(void){
LegoPiece *piece1 = new LegoPiece(RED, 2,1,1);
LegoPiece *piece2 = new LegoPiece(BLUE, 2,2,1);
LegoPiece *piece3 = new LegoPiece(YELLOW, 1,3,2);
std::cout << *piece3 << std::endl;
Box box("CheapBox1");
box.Add(piece1);
box.Add(piece2);
box.Add(piece3);
//cout << box << endl;
return 0;
}