3

我的问题:当一个结构有 c-tor 时,为什么我不能静态初始化它?

我的编译器声称:

type `myStruct' must be initialized by constructor, not by `{...}'

这是为什么 ?我正在使用 gcc 3.4.4 版(cygming 特殊,gdc 0.12,使用 dmd 0.125)

为了说明,这里是struct编译器拒绝的。

struct myStruct
{
    int a;
    double b;

    myStruct() { a= 0; b = 0.0; }
}

void main()
{
    myStruct ms = {7, 7.7}; // Now this compiler does not accept.
} 
4

4 回答 4

7

包含用户定义的 c-tor 意味着它不再是聚合类型。如果自身没有用户定义的 c-tor ,但您有一个非POD 或聚合类型struct的非静态数据成员,也会出现这种情况。struct

于 2012-08-28T15:47:37.470 回答
4

因为语言以这种方式指定它......

原因是构造函数是将对象初始化为有效状态的指定方式,因此直接将值转储到字段中是没有意义的。想法是你要么有一个值的集合,要么有一个自包含的对象,但你想做的事情会两者兼而有之。

于 2012-08-28T15:50:38.497 回答
3

只有聚合可以使用初始化列表进行初始化。根据 8.5.1:1,包含用户提供的构造函数可防止结构或类成为聚合:

8.5.1 聚合 [dcl.init.aggr]

1 - 聚合是一个数组或一个类(第 9 条),没有用户提供的构造函数 [...]

在 C++03 中,

8.5.1 - 聚合 [dcl.init.aggr]

1 - 聚合是一个数组或一个类(子句类),没有用户声明的构造函数 [...]

聚合不同于 POD ( 9:10);并非所有聚合都是 POD,也不是所有 POD 都是聚合;具有用户提供的析构函数的类可以是聚合但不是 POD,而具有非复制非默认构造函数的类可以是 POD 但不是聚合。

示范:

#include <type_traits>
#include <iostream>

struct non_pod_aggregate { int i, j; ~non_pod_aggregate() {} };
struct non_aggregate_pod { int i, j; non_aggregate_pod(int) {}
    non_aggregate_pod() = default; };

int main() {
    std::cout << std::is_pod<non_pod_aggregate>::value << '\n'; // false
    std::cout << std::is_pod<non_aggregate_pod>::value << '\n'; // true
    non_pod_aggregate{0, 0};
    // non_aggregate_pod{0, 0}; // does not compile
}

在 C++03 中,所有 POD ( 9:4) 都是聚合,但仍有可能存在不是 POD 的聚合;如上所述,用户提供的析构函数足以使结构失去 POD 的资格。

于 2012-08-28T15:57:37.873 回答
1

在 C++03 中,列表初始化仅适用于聚合。您需要更改代码以调用构造函数:

myStruct ms;

如果您希望能够为所有成员指定值,则需要添加一个带有足够参数的构造函数:

struct myStruct
{
    int a;
    double b;

    myStruct() : a(), b() { }
    myStruct(int a, double b) : a(a), b(b) { }
};

void main()
{
    myStruct ms(7, 7.7);
} 
于 2012-08-28T15:48:38.703 回答