C++ 为什么大括号或相等初始值设定项为大括号或相等? #包括 #包括 结构{ //std::vector ns(1);//错误! std::vector ns=std::vector(1); }; int main(){ S S; std::cout

C++ 为什么大括号或相等初始值设定项为大括号或相等? #包括 #包括 结构{ //std::vector ns(1);//错误! std::vector ns=std::vector(1); }; int main(){ S S; std::cout,c++,C++,这个想法是完全拒绝任何可以解释为函数声明的语法 #include <iostream> #include <vector> struct S { //std::vector<int> ns(1); //ERROR! std::vector<int> ns = std::vector<int>(1); }; int main() { S s; std::cout << (s.ns[0] =

这个想法是完全拒绝任何可以解释为函数声明的语法

#include <iostream>
#include <vector>

struct S {
    //std::vector<int> ns(1); //ERROR!
    std::vector<int> ns = std::vector<int>(1);
};

int main() {
    S s;
    std::cout << (s.ns[0] = 123) << std::endl;
    return 0;
}

是不允许的,这样可以避免重复最麻烦的解析失败。

为什么要编写
T();
而不是
T;
?@xiver77这是值初始化与默认初始化。如果
T
是内置类型,或者是具有内置成员的聚合,则会产生不同:值初始化导致零初始化,而默认初始化不会。
std::vector<int> ns();
std::vector<int> ns{};
std::vector<int> ns = std::vector<int>();
T t(args...);