Add Object to Array of Objects in C++

2019-05-07 00:06发布

问题:

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?

回答1:

I think you need to change your 'container' declaration:

Shape *ShapeList[30];

void addShape(Shape *s)
{
  for(int i=0; i<30;i++)
  {
    if(ShapeList[i])
        { i++;}
    else
        {
            ShapeList[i]=s;
            numShapes++;
            break;
        }
   }
}

and call addShape this way:

addShape(new Shape());


回答2:

ShapeList[i] returns an object of type Shape. In that case, you can overload operator != (char).

class Shape
{
//your implementation
//
public:
   bool operator != (char x) const
   {
     // comparison logic
   }
};

Also, I believe you have a mistake here:

if(ShapeList[i] != '\0')
    { i++;}

I assume you want to skip this case, but you already increment i in the for loop. You probably want:

if(ShapeList[i] != '\0')
    { continue;}

As others have pointed out, you should use a std::vector instead of a raw array. I initially assumed ShapeList was a wrapper over a std container.



回答3:

Shape * ShapeList[30];   
  numShapes=0;   

     void addShape(Shape* s)
        {
            if( i>=30)
                return;
            ShapeList[numShapes++]=s;      // provided you need to insert at end
        }

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()



回答4:

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?



回答5:

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 a Shape object to a char like you do.

You should be using a std::vector or std::array and use the at member function to see if entry exists or not.



标签: c++ arrays oop