调用错误的操作员

Wrong operator being called

这就是问题所在,我正在尝试重载 operator+=(),我想我已经成功地做到了,但是当我调用 foo += bar 时,编译器指出我对 operator+() 的操作数无效。有谁知道为什么会这样?代码示例如下:

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--;
  }

本质上,Array class 是 Recipe 对象的集合 class,而 UImanager class 是用户交互发生的地方。

您的变量 tempArr 的类型为 Array *,但您应该将 operator+() 应用于 Array 类型的对象,而不是指针(配方相同):

*tempArr += *tempRecipe;

注意:如果你想在指向Recipe的指针上使用operator+(),你可以将参数改为指针而不是引用,但你不能对Array做同样的事情,因为这种形式的 operator+=() 必须应用于对象。否则你必须明确地调用它:

tempArr->operator+=( *tempRecipe );

在任何一种情况下,参数都应为 const Recipe &const Recipe *,因为您不希望修改对象。