使用运算符的隐式转换 [英] Implicit conversion with operator

查看:228
本文介绍了使用运算符的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这部分地受到这个问题。当我写代码:

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被隐式地从 const char * 转换为 std :: string ,我得到预期的输出。但是,当我尝试这样:

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

我得到编译器错误, 'int'and'const char [2]'to binary'operator *' c> c> 未隐式转换为 std :: string const char * 。为什么编译器能够在函数调用的情况下确定隐式转换的需要,但不是对于运算符的情况?

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?

推荐答案

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

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


如果表达式中的运算符没有操作数类型是类或枚举,运算符
假设是一个内置运算符,并根据第5条解释。

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)

([over.match.oper]/1)

这篇关于使用运算符的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆