There is an array of objects and to add object to it i tries the following:
Shape ShapeList[30];
void addShape(Shape s)
{
for(int i=0; i<30;i++)
{
if(ShapeList[i] != '\0')
{ i++;}
else
{
ShapeList[i]=s;
numShapes++;
break;
}
}
}
numShapes is an integer variable, Shape is the class and ShapeList is the array of objects. But the compiler gives an error in this way that !=
operator is not allowed. So how can i implement this?
I think you need to change your 'container' declaration:
and call addShape this way:
You can't use
\0
because it's an array, not a string.storing the whole object as such is an overhead with memory. pointers are a better choice unless you have local variables going out of scope problems. and if STL and Vectors is not beyond your scope of the project you are on to try using it. in which you can use pushback() or pushfront()
ShapeList[i]
returns an object of typeShape
. In that case, you can overloadoperator != (char)
.Also, I believe you have a mistake here:
I assume you want to skip this case, but you already increment
i
in thefor
loop. You probably want:As others have pointed out, you should use a
std::vector
instead of a raw array. I initially assumedShapeList
was a wrapper over astd
container.You did not specify how
ShapeList
is declared.With the != operator you compare it to the character NUL, while 4 lines below you assign it a Shape object.
What i think you are trying to achieve, is: find an empty slot in the array of pointers to Shape, and store the Shape there.
But probably better is to use either a std::vector, or std::list, and push_back your shape.
Another thing you have to ask yourself: do i want to store copies of my Shape object, or pointers?
Unless you have a conversion operator in the
Shape
class to convert it to a character, or a not-equal comparison operator that takes a character as argument, you can not compare aShape
object to achar
like you do.You should be using a
std::vector
orstd::array
and use theat
member function to see if entry exists or not.