Implicit conversion with operator

冷暖自知 提交于 2019-12-19 05:33:15

问题


This is in part inspired by this question. When I write the code:

void test(std::string inp)
{
  std::cout << inp << std::endl;
}

int main(void)
{
  test("test");
  return 0;
}

"test" is implicitly converted from const char* to std::string, and I get the expected output. However, when I try this:

std::string operator*(int lhs, std::string rhs)
{
  std::string result = "";

  for(int i = 0; i < lhs; i++)
  {
    result += rhs;
  }

  return result;
}

int main(void)
{
  std::string test = 5 * "a";
  return 0;
}

I get the compiler error, invalid operands of types 'int' and 'const char [2]' to binary 'operator*'. "a" was not implicitly converted to std::string here, instead it remained a const char*. Why is the compiler able to determine the need for an implicit conversion in the case of a function call, but not for the case of an operator?


回答1:


Indeed, operators have different rules from other kinds of functions.

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

([over.match.oper]/1)



来源:https://stackoverflow.com/questions/33573164/implicit-conversion-with-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!