Declare array of fixed length in nested classes

 ̄綄美尐妖づ 提交于 2019-12-02 00:23:32

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.

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

You can't declare an array of variable size in C++. The compiler must know the size of the array in advance. Use std::vector instead and then use std::vector::shrink_to_fit to reduce its capacity to fit its size.:

class B {
  ...
  std::vector<int> a;
  ...
};

There are two issues. First, note nesting of classes is for scope only. A nested class doesn't automatically create a data member of that class in the outer class. So normally you would then define member(s), in the outer class, of the nested class type as shown below. Second, you can't define an array based on a size that is computed at run-time in C++.

That said, you could easily use a std::vector. If it all has to be done in the header file for some reason, you could define them in-class, though that would be a bad idea if they were more than a couple lines.

#include <vector>
#include <cstddef>

class A {
    private:
        class B {
            friend A;
            B(size_t n) : array(n) {}
            std::vector<int> array;
        };
    public:
        // Initialize b_member based on some computation.
        A(int i) : b_member(i + 2), b_ptr_member(new B(i + 3)) {}
        ~A() { delete b_ptr_member; }
    private:
        B b_member;
        B *b_ptr_member;
};

int main() {
    A a(10);
}

The answer is: use std::vector. This item:

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

does not really apply. You do need extra functionality that old good arrays do not have (namely, allocating an array for which you only have the size at run time).

If you have a recent compiler/standard library, maybe you have access to <experimental/dynarray>... which, IMHO, is just a crippled version of <vector>, but to each, its own :D

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!