使用运算符

时间:2015-11-06 18:18:59

标签: 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;
}

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

1 个答案:

答案 0 :(得分:8)

实际上,运营商与其他类型的职能有不同的规则。

  

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

([over.match.oper] / 1)

相关问题