gpt4 book ai didi

c++ - 将 static const char[] 设置为预定义的 static const char[] 失败

转载 作者:太空狗 更新时间:2023-10-29 23:34:42 24 4
gpt4 key购买 nike

大家好!当我尝试在头文件中执行以下操作时

static const char FOOT[] = "Foot";
static const char FEET[] = FOOT;

我收到编译器错误 error: initializer fails to determine size of FEET。我想知道这是什么原因,是否有办法纠正它。谢谢!

最佳答案

尽管您得到此错误的原因已得到解答,但故事还有更多内容。如果您确实需要 FEET 是一个数组,那么您可以将其设为引用而不是指针:

char const foot[] = "foot";

char const (&feet)[sizeof foot] = foot;
// reference to array (length 5) of constant char
// (read the declarations "from the inside-out")

char const* const smelly_feet = foot;
// constant pointer to const char

int main() {
cout << sizeof feet << ' ' << feet << '\n';
cout << sizeof smelly_feet << ' ' << smelly_feet << '\n';
cout << sizeof(void*) << " - compare to the above size\n";
return 0;
}

(inside-out rule 的更多示例。)

其次,static at file and namespace scope表示内部链接;因此,当您在标题中使用它时,您将在每个使用该标题的 TU 中获得重复的对象。有些情况下您需要这样做,但我在您的代码中看不到这样做的理由,这是一个常见错误。

关于数组大小: sizeof 运算符返回对象或类型实例的内存大小。对于数组,这意味着其所有项的总内存大小。由于 C++ 保证 sizeof(char) 为 1,因此 char 数组的内存大小与其长度相同。对于其他数组类型,您可以除以一项的内存大小以获得数组的长度:

void f() {
int array[5];
assert((sizeof array / sizeof *array) == 5);
}

并且您可以将其概括为一个函数模板:

template<class T, int N>
int len(T (&)[N]) {
return N;
}
// use std::size_t instead of int if you prefer

这在 boost 中作为 boost::size 存在.

您可能会看到使用 sizeof array/sizeof *array 的代码,无论是通过宏还是直接,因为它是旧的或不想使事情复杂化。

关于c++ - 将 static const char[] 设置为预定义的 static const char[] 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1758946/

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