gpt4 book ai didi

c++ - 无法从成员变量中的初始化字符串推断数组大小的原因是什么?

转载 作者:IT老高 更新时间:2023-10-28 22:21:03 25 4
gpt4 key购买 nike

考虑代码:

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

int main()
{
Foo foo;
}

g++ 和 clang++ 都无法编译,基本上是吐出来

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

我知道标准可能是这样说的,但是有什么特别好的理由吗?由于我们有一个字符串文字,因此编译器似乎应该能够毫无问题地推断出大小,类似于您简单地声明一个类外 const 类似 C 的空终止字符串的情况.

最佳答案

原因是您始终可以在构造函数中覆盖类内初始化程序列表。所以我猜到最后,它可能会很困惑。

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 char 效果很好,而且可能这正是您想要的。

关于c++ - 无法从成员变量中的初始化字符串推断数组大小的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com