带运算符的隐式转换
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*
。为什么编译器能够在函数调用的情况下确定是否需要隐式转换,而在运算符的情况下却不能确定?
实际上,运算符与其他类型的函数有不同的规则。
如果表达式中运算符的操作数的类型不是类或枚举,则运算符假定为内置运算符,并根据第5条进行解释。
([over.match.oper]/1)
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 继承模板化转换运算符
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在模板化转换运算符中消除此构造的歧义?
- 为什么选择转换运算符的重载?
- 如何避免强制转换运算符 () 和访问运算符 [] 冲突?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 了解转换运算符的选择C++
- 多个隐式转换运算符
- 这个typedef和转换运算符语法是什么意思
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 类模板忽略了用户定义的转换运算符(非模板不忽略)
- 为什么在std::for_each()返回时调用转换运算符
- 为什么 std::optional 的强制转换运算符被忽略了
- 使用用户定义的转换运算符推导函数模板参数
- 模板转换运算符的分辨率不明确
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?