在成员变量中无法从initializer-string中推导出数组大小的原因是什么? [英] What is the reason for not being able to deduce array size from initializer-string in member variable?

查看:2431
本文介绍了在成员变量中无法从initializer-string中推导出数组大小的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑代码:

struct Foo
{
    const char str[] = "test";
};

int main()
{
    Foo foo;
}

无法使用g ++和clang ++编译, >

It fails to compile with both g++ and clang++, spitting out essentially



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




我知道这是标准可能说的,原因?因为我们有一个字符串字面量,似乎编译器应该能够推导出大小没有任何问题,类似于当你简单地声明一个out-of-class const C类空结束字符串。

I understand that this is what the standard probably says, but is there any particular good reason why? Since we have a string literal it seems that the compiler should be able to deduce the size without any problem, similarly to the case when you simply declare an out-of-class const C-like null terminated string.

推荐答案

原因是你总是有可能重写一个类初始化列表构造函数。所以我猜这最后可能很混乱。

The reason is that you always have the possibility to override an in class initializer list in the constructor. So I guess that in the end it could be very confusing.

struct Foo
{
   Foo() {} // str = "test\0";

   // Implementing this is easier if I can clearly see how big `str` is, 
   Foo() : str({'a','b', 'c', 'd'}) {} // str = "abcd0"
   const char str[] = "test";
};

请注意,将 const char 替换为 static constexpr 工作完美,可能这是你想要的

Notice that replacing const char with static constexpr works perfectly, and probably it is what you want anyway

这篇关于在成员变量中无法从initializer-string中推导出数组大小的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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