使用 struct Initializer 为 public 成员变量赋值不会产生编译器错误?

Using struct Initializer to assign values to public member variables doesn't generate compiler error?

在下面的 C++ 代码中,为什么与赋值运算符一起使用的结构初始值设定项不会产生编译器错误?

是否是编译器错误?

它适用于所有编译器吗?

实际上是哪种作业?

class vector2D
{
    public :
        double x,y;
};

int main()
{
    vector2D v1;
    v1 = {1,2} ; // why does this compile and work?
}

赋值的右侧可以是 braced-init-list:它被转换为某种适当类型的值(通常是左侧类型)分配。它可以如此转换只是 aggregate 初始化,甚至 C 也一直以某种形式存在(并且最近 复合文字 )。

当 class 没有显式定义的赋值运算符时,存在隐式定义的赋值运算符。

在你的例子中,有一个形式为

的隐式定义的复制赋值运算符
vector2D& operator=(vector2D const& rhs);

您可以在此类赋值的右侧使用任何表达式,只要它可以转换为 vector2D const&。在您的情况下, {1, 2} 确实满足该要求。因此,

v1 = {1,2};

没问题。就好像你曾经使用过:

v1 = vector2D{1,2};

Is it a compiler bug ?

没有。

Will it work on every compiler ?

它将在所有 C++11(或更高版本)兼容的编译器上编译。

Which kind of assignment is it actually ?

这是从使用列表初始化创建的临时对象赋值。