简体   繁体   English

C ++类,数组成员的大小由CTOR传递

[英]C++ class with array member with size passed by CTOR

Why I cannot have m_data array as a member like this? 为什么我不能像这样将m_data数组作为成员?

class Array
{
private:
    const int m_capacity;
    int m_data[m_capacity];

public:
    Array(const int capacity = 100);
};


Array::Array(const int capacity /*= 100*/)
    : m_capacity(capacity)
{

}

And how I can achieve this without dynamic memory allocation? 在没有动态内存分配的情况下如何实现呢?

In this case the compiler can't know the size of class Array and it can't determine size of such object. 在这种情况下,编译器无法知道class Array的大小,也无法确定此类对象的大小。 If objects of indeterminate compile-time size were allowed, the entire language would be different. 如果允许不确定的编译时大小的对象,则整个语言将有所不同。

However, if you know capacity at compile time, you can write 但是,如果您知道编译时的容量,则可以编写

template <int Size = 100>
class Array
{
private:
    int m_data[Size];

public:
    Array();
};

Then, to use it, you can do 然后,要使用它,您可以

Array<> a; //size = 100
Array<250> b; //size = 250

As @Superlokkus mentioned in comment, C++11 std::array is just a better implementation with same concept. 正如@Superlokkus在评论中提到的那样,C ++ 11 std::array只是具有相同概念的更好的实现。

I would suggest use std::array instead of building your own wheel 我建议使用std :: array而不是构建自己的轮子

#include <array>
template< unsigned long N >
using Array = std::array<int, N>;

And use Array as a normal templated class 并使用Array作为常规模板化类

Array<100> arr;

If you are keen on 100-sized array, it is even simpler 如果您热衷于100大小的阵列,则它甚至更简单

using Array = std::array<int, 100>;
Array arr;

Either you can declare a template class like this 您可以声明这样的模板类

#include <iostream>

template <size_t N = 100>
class Array
{
private:
    const size_t m_capacity = N;
    int m_data[N];

public:
    Array();
};

template <size_t N>
Array<N>::Array() : m_data {}
{
}

int main() 
{
    Array<> a1;
    Array<10> a2;

    return 0;
}

Or you should use data member 或者您应该使用数据成员

std::vector<int> m_data;

instead of the array. 而不是数组。

You can't have an object whose size is chosen at runtime without dynamic allocation. 如果没有动态分配,就不能拥有在运行时选择大小的对象。 You can have it without naked new / delete ; 您可以不带任何new / delete就拥有它; the normal class encapsulating that requirement is std::vector . 封装该要求的普通类是std::vector

Alternatively, you can have a family of classes of different sizes. 另外,您可以拥有一系列不同大小的类。 The normal class for that is std::array . 普通的类是std::array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM