它用 /permissive
编译,但用 /permissive-
编译失败。什么不符合要求以及如何解决?
为什么在 (2)
中没问题,但在 (4)
(3)
中失败了?
如果我删除 operator long
也可以。
如何在不更改调用站点 (3,4)
的情况下修复它?
#include <string>
struct my
{
std::string myVal;
my(std::string val): myVal(val) {}
operator std::string() { return myVal; };
operator long() { return std::stol(myVal); };
};
int main()
{
struct MyStruct
{
long n = my("1223"); // (1)
std::string s = my("ascas"); // (2)
} str;
str.s = my("ascas"); // (3)
str.n = my("1223"); // (4)
}
错误信息
error C2593: 'operator =' is ambiguous
xstring(2667): note: could be 'std::basic_string<...> &std::basic_string<...>::operator =(const _Elem)'
with
[
_Elem=char
]
xstring(2648): note: or 'std::basic_string<...> &std::basic_string<...>::operator =(const std::basic_string<...> &)'
xstring(2453): note: or 'std::basic_string<...> &std::basic_string<...>::operator =(std::basic_string<...> &&) noexcept(<expr>)'
Source1.cpp(17): note: while trying to match the argument list '(std::string, my)'
最佳答案
我想你的意思是它在 (2) 中很好,但在 (3) 中失败了
注意 #2 是初始化,它调用 constructor of std::string
; #3 是赋值,它调用 assignment operator of std::string
.它们是不同的东西。
赋值运算符的调用是不明确的,因为 std::string
的赋值运算符有一个采用 char
的重载,它可以从 long< 隐式转换
(这是标准转换),然后导致歧义(赋值运算符采用 std::string
,正如编译器所提示的那样)。 implicit conversion sequence包含一个用户定义的转换(从 my
到 std::string
或 long
),它们在 onverload resolution 中具有相同的等级.
构造函数的调用很好,因为它没有这样的重载(采用char
)。
关于c++ - msvc/permissive- std::string 重载运算符 '=' 不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821371/