C++ C2100 初始化结构变量时非法间接

问题描述 投票:0回答:3

我正在使用“VS2017 Community”,平台 Windows 7。当尝试执行下一步时,我收到错误 C2100:

struct Conf {
    unsigned int id;
    int test1;
    int test2;
    int test3;
    int test4;
    int test5;
    int test6;
};

Conf cf({
    0,
    0,
    0,
    0,
    0,
    0,
    0
}); //<-- Here is error - C2100 Illegal Indirection

谁能告诉我这里可能出现什么问题吗?谢谢。

c++ visual-studio-2017
3个回答
4
投票

该结构没有构造函数。您想要的代码如下:

struct Conf {
    unsigned int id;
    int test1;
    int test2;
    int test3;
    int test4;
    int test5;
    int test6;
};

Conf cf = {
    0,
    0,
    0,
    0,
    0,
    0,
    0
}; // Array initializer for struct type.

2
投票

取下圆括号。编译器正在尝试使用构造函数。

#include <iostream>
struct Conf {
    unsigned int id;
    int test1;
    int test2;
    int test3;
    int test4;
    int test5;
    int test6;
};

Conf cf {  // Curlies only
    1u,
    0,
    0,
    0,
    0,
    0,
    7
}; 

int main() {
    std::cout << cf.id << " " << cf.test6 << '\n';
    return 0;
}

0
投票

我相信问题是最令人烦恼的解析在哪里

Conf cf({..});
被理解为一个以 temp
Conf
对象作为参数的函数。

temp

Conf
对象已列表初始化,如下所示。

来自

dcl.init#17.1

如果初始化器是一个(非括号)大括号初始化列表或者是= braced-init-list,对象或引用是list-initialized

struct S2 {
  int m1;
  double m2, m3;
};
S2 s21 = { 1, 2, 3.0 }; // OK
S2 s22 { 1.0, 2, 3 };   // error: narrowing

所以直接列表初始化

cf

Conf cf {...};
© www.soinside.com 2019 - 2024. All rights reserved.