阵列中的数据成员没有大小声明 [英] Array data members declared with no size
问题描述
我想了解数组用C如何工作++。在SO一些好的线程,但我有一个问题,我无法找到答案的是:
I'm trying to understand how arrays work in C++. Some good threads on SO, but one question I have that I can't find the answer to is:
为什么能阵列中的数据成员没有大小申报?我在C ++中想到了一个数组的大小必须是一个编译时间常数?
Why is it possible to declare array data members with no size? I thought in C++ an array size had to be a compile-time constant?
例如:
#include<iostream>
class Object{
public:
Object(std::size_t n){
for(std::size_t i = 0; i<n; ++i) { array[i] ='X'; }
//prints 0 because 'sizeof' is compile-time operator
std::cout << "compile-time size: " << sizeof(array) << std::endl;
std::cout << "run-time size " << n << std::endl;
}
private:
char array[];
};
int main( int argc, char** argv )
{
Object obj(10); //10 chars
std::size_t n;
std::cin >> n;
Object obj2(n); //n chars in automatic storage i.e. on the stack??
}
Input:
n = 1000
Output:
compile-time size: 0
run-time size 10
compile-time size: 0
run-time size 1000
这是否意味着OBJ2的阵列数据成员被存储在自动存储,但大小是在运行时动态确定?
Does this mean that obj2's array data member is stored in automatic storage, but the size is determined dynamically at runtime ?
感谢
推荐答案
根据C ++标准(9.2类成员)
According to the C++ Standard (9.2 Class members)
9 非静态(9.4)数据成员不得有不完全类型即可。在
特别是C类,不得包含类的非静态成员
C,但它也可以包含一个指针或引用类C的一个对象。
9 Non-static (9.4) data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C.
那么它要么是一个编译器特性及其错误。
So it is either a compiler feature or its bug.
作为一类的非静态数据成员的数组存储在哪里该类别对应的对象被分配
An array as a non-static data member of a class is stored where the corresponding object of that class was allocated.
至于C,那么C允许定义结构的灵活数组成员。
As for C then C allows to define flexible array members of structures.
从C标准(6.7.2.1结构和联合说明符)
From the C Standard (6.7.2.1 Structure and union specifiers)
18作为一个特例,一个结构与以上的最后一个元素
一个命名的成员可能有一个不完全数组类型;这就是所谓的
灵活的数组成员
18 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member
但在这种情况下,结构应有的多个命名成员
But in this case a structure shall have more than one named member.
这篇关于阵列中的数据成员没有大小声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!