【问题标题】:error: initialization with "{...}" expected for aggregate object - c++错误:聚合对象需要使用“{...}”进行初始化 - C++
【发布时间】:2014-02-21 02:55:51
【问题描述】:
struct test
{
    unsigned int test1;
    unsigned char test2[4096];
    unsigned int test3;
} foo

struct foobar
{
unsigned char data[4096];
}

如果我想访问该结构,我会说 foo.test1、foo.test2[4096] 等。 但是,当我希望以下列方式返回 foo.test2 中存在的数据时

pac.datafoo = foo.test2[4096];

unsigned char data[4096] =  pac.datafoo;

这是我得到的错误:

error: initialization with "{...}" expected for aggregate object

我做错了什么?

【问题讨论】:

  • 我还有什么需要提供的信息吗?
  • 是的:pac 是什么,datafoo 是什么,...
  • Pac 也是一个结构体。 datafoo 是一个无符号字符。
  • 您的test 类中没有datafoo 成员...
  • 顺便说一句,foo.test2[4096] 越界

标签: c++ data-structures


【解决方案1】:

你需要学习数组初始化方法。它不是简单地分配为单个变量。

一些例子:

int arrayone[3] = {0}; // assign all items with 0

int arraytwo[3] = {1, 2, 3 }; // assign each item with 1, 2 and 3

int arraythree[3]; // assign arraythree with arraytwo
for (int i = 0; i < 3; ++i) {
    arraythree[i] = arraytwo[i];
}

【讨论】:

  • 注意int arrayone[3] = {0};它只分配所有元素0,因为这是默认值,最后两个元素是这样构造的。同样,int a[3] = {}; 将它们全部分配给0;然而,这里的重要区别是int a[3] = {2}; 确实 将它们全部分配2 - 第一个元素分配给2,其他元素默认构造为0
【解决方案2】:

添加“;”在结构的末尾。

struct test
{
    unsigned int test1;
    unsigned char test2[4096];
    unsigned int test3;
} foo ;

struct foobar
{
unsigned char data[4096];
} ;

【讨论】:

    【解决方案3】:
    unsigned char * data;
    
      data = pac.datafoo;
    

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 2017-02-27
      • 2015-04-24
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      相关资源
      最近更新 更多