为什么编译器不能像结构体成员一样为变量声明设置char [] = {..}的大小? [英] Why the compiler can't set size of char[] = { .. } in a struct member like it does for a variable declaration?

查看:178
本文介绍了为什么编译器不能像结构体成员一样为变量声明设置char [] = {..}的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在结构中使用 struct 和初始化的值,如下面的例子。我不能理解的是为什么编译器不能设置大小 char [] = {..} 在一个结构成员像它为一个变量声明? Clang ++给出以下错误:

I'm using struct with initialized value inside a struct, like below example. What I can't understand is why the compiler can't set size of char[] = { .. } in a struct member like it does for a variable declaration? Clang++ gives the following error:


错误:无法从类初始化器中推导出数组bound

error: array bound cannot be deduced from an in-class initializer

代码:

struct A
{
    char s[]   = { 'F', 'O', 'O', ... };
};


推荐答案

结构元素创建时无法初始化,因为结构定义了一个类型而不是一个可以初始化的变量。您只能在创建结构的对象后初始化结构的变量

Structure elements cannot be initialized while they're created, because the structure defines a type and not a variable which can be initialized. You can only initialize a variable of a structure after creating an object of a structure

例如

struct test
{
    int var;
};

struct test struct_object = { 7 };

这篇关于为什么编译器不能像结构体成员一样为变量声明设置char [] = {..}的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆