带运算符的隐式转换

Implicit conversion with operator

本文关键字:转换 运算符      更新时间:2023-10-16

这在一定程度上受到了这个问题的启发。当我写代码时:

void test(std::string inp)
{
  std::cout << inp << std::endl;
}
int main(void)
{
  test("test");
  return 0;
}

"test"被隐式地从const char*转换为std::string,我得到了预期的输出。然而,当我尝试这个:

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

我得到了编译器错误invalid operands of types 'int' and 'const char [2]' to binary 'operator*'"a"在这里没有隐式地转换为std::string,而是保持为const char*。为什么编译器能够在函数调用的情况下确定是否需要隐式转换,而在运算符的情况下却不能确定?

实际上,运算符与其他类型的函数有不同的规则。

如果表达式中运算符的操作数的类型不是类或枚举,则运算符假定为内置运算符,并根据第5条进行解释。

([over.match.oper]/1)