本文介绍了在声明嵌套类固定长度的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有A类,它有一个嵌套类B级A,将创建N(运行时间参数)B类的实例。

I have a class A, which has a nested class B. Class A, will create n(run time parameter) instances of class B.

在A的构造函数,以后需要在运行时进行计算,计算我的尺寸,让我们们的说法。

In the constructor of A, after computations that need to be made at run time, I compute a size, let's say s.

现在,每一个B类,将举办大小的数组中。

Now, every class B, will hold an array of size s.

不过,我不允许使​​用.cpp文件和所有的工作必须在头文件中完成。

However, I am not allowed to use .cpp files and all the work must be done in header files.

这意味着,据我了解,我不能使用这些方法(用静态

This means, as far as I understand, that I can not use these approach (with static):

class B {

static const int s;
int a[s];

};

所以,我决定用枚举,但我不能使它工作(甚至与枚举类 C ++的11)。
这个想法是,你做的是这样的:

So, I decided to use enum, but I couldn't make it work (even with enum class of C++11).The idea is that you do something like:

class B {

enum { s = 50 };
int a[s];

};

但我不知道取值运行时间之前。

当然,我可以用的std ::矢量去动态分配

但自从:

1)我只需要老好阵列的功能(丢弃矢量)

1)I need only the functionality of the old good arrays (discards vector)

2)我知道构造B的情况下,数组的大小(丢弃动态分配之前)

2)I know before constructing the instances of B, the size of the array (discards dynamic allocation)

关于的std ::的DynArray 讨论如下:

可惜不是 C ++ 14 ,而在阵列TS C + +17
,要归功于manlio。

Unfortunately not in C++14, but in array TS or C++17.Source, credits to manlio.

放弃是一个沉重的词。我的意思是,我听说自动分配速度更快,但动态分配,可以让你分配更多的空间。此外,载体,在释放模式,正在做的并不坏与阵列比较。

Discard is however a heavy word. I mean, I have heard that automatic allocation is faster, but dynamic allocation lets you allocate more space. Moreover, vectors, in the release mode, are doing not that bad in comparison with the arrays.

推荐答案

有偶数,但具有不同的尺寸相同的元素类型两个数组不同的类型。因此,例如的char [10] 的char [11] 是不同的类型。同样的方式,如果两个类都与这两个类则类定义了不同类型和大小不同(我指的sizeof操作符)之间的不同类型的成员。你也可以不实例化一个不完整的类型的对象。

Two arrays having even the same element type but with different sizes are different types. So for example char[10] and char[11] are different types. The same way if two classes have a member with a type that differs between these two classes then the classes define different types and have different sizes (I mean operator sizeof). Also you may not instantiate an object of an incomplete type.

如果你的编译器支持类的std ::的DynArray 我会建议使用它。否则,你可以使用类的std ::矢量

If your compiler supports class std::dynarray I would advice to use it. Otherwise you can use class std::vector

这篇关于在声明嵌套类固定长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:01