Sythe
Sythe

Reputation: 143

Wrong operator being called

Here's the problem, I'm trying to overload operator+=() and I think I successfully have done so, but when I call foo += bar the compiler states that I have invalid operands for operator+(). Does anyone know why this might be happening? Example of the code is below:

Array& Array::operator+=(Recipe& recipe){ //Adds a Recipe object to Array object and orders
  int i = 0;

  if (size == MAX_RECIPES)
    return;

  while(i!=size && recipe.getName() > recipes[i]->getName()) //Order
    i++;

  for(int j=size; j>i; j--) //Shift to fit new recipe
    recipes[j] = recipes[j-1];
  recipes[i] = &recipe;
  size++;
  return *this;
}


void UImanager::addRecipes(Array *arr){ //Adds multiple Recipe objects to a temporary Array object
  int i;
  cout << endl << "Enter the number of recipes you wish to add: ";
  cin >> i;
  if(i<0)
    return;

  Array *tempArr = new Array;
  while(i){
    Recipe *tempRecipe = new Recipe;
    getRecipeData(tempRecipe);
    tempArr += tempRecipe;
    i--;
  }

In essence, the Array class is a collection class for Recipe objects, and the UImanager class is where user interaction takes place.

Upvotes: 0

Views: 92

Answers (1)

Slava
Slava

Reputation: 44258

You variable tempArr has type Array * but you should apply operator+() to an object of type Array not a pointer (same for recipe):

*tempArr += *tempRecipe;

Note: if you want to use operator+() on a pointer to Recipe, you can change parameter to pointer instead of reference, but you cannot do the same with Array, as operator+=() in this form has to be applied on object. Otherwise you have to call it explicitly:

tempArr->operator+=( *tempRecipe );

in either case parameter should be const Recipe & or const Recipe * as you do not expect object to be modified.

Upvotes: 2

Related Questions