作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
大家好!当我尝试在头文件中执行以下操作时
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/
我是一名优秀的程序员,十分优秀!