2015-11-06 77 views
9

这部分受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*。为什么编译器能够在函数调用的情况下确定是否需要隐式转换,而不是运算符的情况?

回答

8

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

如果在表达式无操作者的操作数具有类型,它是一个类或一个枚举,操作员被假定 是一个内置的操作和解释根据条款5.

([over.match.oper]/1)

+3

通常我会说,“为了完整性添加第5条。”但五十页的页面似乎过度。 – user4581301

+0

事实上,隐式转换的工作方式与非原始类型相同;见[这里](http://ideone.com/K4K2vS)。 –