如何在类中使用常量类变量声明常量数组?
如何在类中使用常量类变量声明常量数组?是否可以。 我不想要动态数组。
我的意思是这样的:
class test
{
const int size;
int array[size];
public:
test():size(50)
{}
}
int main()
{
test t(500);
return 0;
}
上面的代码给出了错误
How to declare a constant array in class with constant class variable? Is it possible.
I don't want dynamic array.
I mean something like this:
class test
{
const int size;
int array[size];
public:
test():size(50)
{}
}
int main()
{
test t(500);
return 0;
}
the above code gives errors
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这是不可能的:只要
size
是动态变量,array[size]
就不可能实现为静态数组。如果您愿意,可以这样考虑:
sizeof(test)
必须在编译时已知(例如考虑test
数组)。但是在您的假设示例中,sizeof(test) == sizeof(int) * (1 + size)
,这不是编译时已知值!可以将
size
作为模板参数;这是唯一的解决方案:用法:
Test<50>; x;
请注意,现在我们有
sizeof(Test) == sizeof(int) * (1 + N)
,这实际上是一个编译时已知值,因为对于每个N
,Test
是一个不同类型。No, it's not possible: As long as
size
is a dynamic variable,array[size]
cannot possibly be implemented as a static array.If you like, think about it this way:
sizeof(test)
must be known at compile time (e.g. consider arrays oftest
). Butsizeof(test) == sizeof(int) * (1 + size)
in your hypothetical example, which isn't a compile-time known value!You can make
size
into a template parameter; that's about the only solution:Usage:
Test<50> x;
Note that now we have
sizeof(Test<N>) == sizeof(int) * (1 + N)
, which is in fact a compile-time known value, because for eachN
,Test<N>
is a distinct type.你的意思是固定大小的数组?您可以像这样使用 std::array :
或者,如果您想支持不同的大小,则需要求助于这样的类模板:
std:array 有额外的好处保留大小信息与成员(与衰减为指针的数组不同)并且与标准库算法兼容。
Boost 还提供了一个版本 (boost::array) 类似。
You mean a fixed sized array? You could use
std::array
like this:Or if you want to support different sizes you need to resort to a class template like this:
std:array
has the added benefit of keeping the size information along with the member (unlike arrays which decay to pointers) and is compatible with the standard library algorithms.There is also a version that Boost offers (boost::array) which is similar.
您的代码会产生错误,因为编译器需要知道每个成员的数据类型的大小。当您编写
int arr[N]
时,成员arr
的类型是“N 个整数的数组”,其中N
必须是编译时已知的数字。一种解决方案是使用枚举:
另一种解决方案是将 size 声明为类的静态 const 成员:
请注意,仅允许静态类整数进行类内初始化!对于其他类型,您需要在代码文件中初始化它们。
Your code yields an error because compiler needs to know the size of data type of each member. When you write
int arr[N]
type of memberarr
is "an array of N integers" whereN
must be known number in compile time.One solution is using enum:
Another is declaring size as static const member of class:
Note that in-class initialization is allowed only for static class integers! For other types you need to initialize them in code file.