c++ - msvc/permissive- std::string 重载运算符 '=' 不明确

标签 c++ visual-c++ implicit-conversion move-constructor move-assignment-operator

它用 /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包含一个用户定义的转换(从 mystd::stringlong),它们在 onverload resolution 中具有相同的等级.

构造函数的调用很好,因为它没有这样的重载(采用char)。

关于c++ - msvc/permissive- std::string 重载运算符 '=' 不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57821371/

相关文章:

C++ : declaring in if/else : var not declared in this scope

c++ - 使用 gdi+ 绘制 hdc 是否会导致预乘 alpha 位图?

c - 当 va_list 的长度由局部变量设置时,vsprintf_s() 不起作用

Scala:隐式参数中的错误

c++ - 如何使 C++ 函数将整数列表隐式转换为 vector 参数?

c++ - 为什么这个 volatile 变量的地址总是为 1?

c++ - 将 4 个整数的组合映射到单个值

c++ - 如何自动确定2D阵列的CUDA block 大小和网格大小?

c++ - 函数不读取和打印 C++ 中的文件内容

c++ - 如何在 Linux 下构建 Visual Studio Solution?