部分灵感来自 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/