小编MYL*_*YLS的帖子

当重载const和非const转换运算符返回数组类型时,MSVC错误C2593

最近,我尝试使用转换运算符作为替代operator [].

像下面的代码:

#include <iostream>

class foo
{
public:
    using type = int[1];

public:
    operator type       &()       { return data; }
    operator type const &() const { return data; }

private:
    type data;
};

int main()
{
    foo f;
    f[0] = 1;                        // error happens here
    std::cout << f[0] << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我发现它适用于G ++,不适用于MSVC v141(2017).

MSVC报道:

error C2593: 'operator [' is ambiguous
note: could be 'built-in C++ operator[(foo::type, int)'
note: or       'built-in C++ …
Run Code Online (Sandbox Code Playgroud)

c++ visual-c++ language-lawyer

8
推荐指数
1
解决办法
206
查看次数

标签 统计

c++ ×1

language-lawyer ×1

visual-c++ ×1