使用运算符的隐式转换
Implicit conversion with operator
这部分受到 问题的启发。当我写代码时:
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*
。为什么编译器能够在函数调用的情况下确定是否需要隐式转换,而在运算符的情况下却不能?
确实,运算符与其他类型的函数有不同的规则。
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)
这部分受到
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*
。为什么编译器能够在函数调用的情况下确定是否需要隐式转换,而在运算符的情况下却不能?
确实,运算符与其他类型的函数有不同的规则。
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)