繁体   English   中英

错误的运算符被调用

[英]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类是Recipe对象的集合类,而UImanager类是进行用户交互的地方。

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

*tempArr += *tempRecipe;

注意:如果要在指向Recipe的指针上使用operator+() ,可以将参数更改为指针而不是引用,但是您不能对Array进行相同的operator+=() ,因为必须将此格式的operator+=()应用于对象。 否则,您必须显式调用它:

tempArr->operator+=( *tempRecipe );

无论哪种情况,参数都应为const Recipe &const Recipe *因为您不希望修改对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM