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"
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;
}
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…