c++ - 使用运算符的隐式转换

标签 c++ operator-overloading

部分灵感来自 this问题。当我写代码时:

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

我收到编译器错误,类型为“int”和“const char [2]”的无效操作数到二进制“operator*”"a" 并未隐式转换为 std::string ,而是保留为 const char*。为什么编译器能够在函数调用的情况下确定是否需要隐式转换,而在运算符的情况下却不能?

最佳答案

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

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)

关于c++ - 使用运算符的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573164/

相关文章:

c++ - stof、strtof是确定性的吗?

c++ - 你能通过保证多个线程不会访问同一个内存来避免锁定吗?

f# - 再次在 F# 中自定义前缀运算符

c++ - 为什么我们不能在构造函数大括号 ({ }) 中初始化 Const 和引用变量,并且总是通过初始化列表完成

c++ - 指向销毁类失效的指针

c++ - 在 C++ 中,所有名称都必须是 "under-the-hood"指针吗?

c++ - 使用模板可视化代码中的2D和3D形状

c# - 重载相等运算符时,处理空值的最佳方式是什么?

c++ - += 在没有 boost 的 vector 上

c++ - 这种重载 operator new 有什么问题吗?