【发布时间】:2010-09-30 13:48:40
【问题描述】:
// sizeofarray.cpp
#include <iostream>
template <typename T,int N>
int size(T (&Array)[N])
{
return N;
}
int main()
{
char p[]="Je suis trop bon, et vous?";
char q[size(p)]; // (A)
return 0;
}
听说 C++ 中的数组大小必须是常量表达式。所以char q[size(p)] 无效,对吗?但是我尝试时没有错误
g++ -Wall sizeofarray.cpp
为什么?
【问题讨论】:
-
q[sizeof(p)]很好,你的意思可能是q[size(p)]。请注意,后者将在 C++0x 中生效(如果您将size声明为constexpr)。 -
问题在于“大小”而不是 sizeof。看我的帖子。
-
尝试编译器选项 -pedantic 或 -std=c++98 ;-)