头文件中的 C++ 数组声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/322086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:38:39  来源:igfitidea点击:

c++ array declaration in a header

c++arraysdynamicheader

提问by JaredPar

I was wondering if it is possible to declare an array (size not known at this time), as a private member of a class and later set the size in the constructor of the class. For example:

我想知道是否可以将数组(此时大小未知)声明为类的私有成员,然后在类的构造函数中设置大小。例如:

class Test {
int a[];
public:
Test(int size);
};

Test::Test(int size) {
a[size];   // this is wrong, but what can i do here?
}

Is this possible or should I use dynamic arrays? Thanks!

这是可能的还是我应该使用动态数组?谢谢!

回答by Martin York

Short Answer: No (The size of an array is defined at compile time only)
Long Answer:

简答:否(数组的大小仅在编译时定义)
长答:

You can use a vector to achieve the same result:

您可以使用向量来实现相同的结果:

class Test
{
    std::vector<int> a;
    public:
        Test(std::size_t size):
            a(size)
        {}
};

回答by JaredPar

No this is not possible. Array declarations in headers must have constant sized value. Otherwise it's impossible for constructs like "sizeof" to function properly. You'll need to declare the array as a pointer type and use new[] in the constructor. Example.

不,这是不可能的。标头中的数组声明必须具有恒定大小的值。否则像“sizeof”这样的结构就不可能正常工作。您需要将数组声明为指针类型并在构造函数中使用 new[]。例子。

class Test { 
    int *a;
public:
    Test(int size) {
       a = new int[size];
    }
    ~Test() { delete [] a; }
private:
    Test(const Test& other);
    Test& operator=(const Test& other);
};

回答by Greg Hewgill

As other answers have pointed out, the size of an array is fixed at compile time. However, by using templates you can parameterise the size at compile time:

正如其他答案所指出的,数组的大小在编译时是固定的。但是,通过使用模板,您可以在编译时参数化大小:

template <int N> class Test {
    int a[N];
public:
    Test() { }
};

Test<5> test;
Test<40> biggertest;

This technique does not let you compute the size at runtime (as the dynamic std::vectorsolution does), but depending on your needs this may be sufficient.

这种技术不允许您在运行时计算大小(就像动态std::vector解决方案那样),但根据您的需要,这可能就足够了。

回答by Uri

First of all, it is generally better to initialize things in the initialization list of the constructor, not in the body of the constructor.

首先,通常最好在构造函数的初始化列表中初始化事物,而不是在构造函数的主体中。

You can only initialize an array with a predefined bound if you know that bound at compile time. In this situation, you will need to dynamically allocate the space.

如果您在编译时知道该边界,则只能使用预定义的边界初始化数组。在这种情况下,您将需要动态分配空间。

You must remember then to have a destructor that would delete the array when the object is destroyed or you would get a memory leak.

你必须记住有一个析构函数,它会在对象被销毁时删除数组,否则你会得到内存泄漏。

回答by orip

See Martin's solution (use std::vector), and remember that even if you need to pass a buffer to a C API std::vectorlets you do it by passing &vec[0]:

请参阅 Martin 的解决方案(使用std::vector),并记住,即使您需要将缓冲区传递给 C API std::vector,您也可以通过传递&vec[0]

std::vector<char> vec(10);
memset(&vec[0], 0, vec.size());

It's guaranteed to work, but only if the vector isn't empty (C++ quirks, <sigh>).

它保证可以工作,但前提是向量不为空(C++ 怪癖,<sigh>)。

回答by Dave

What you're talking about is not possible. Classes always have a constant size. You could have your class use a pointer to a dynamically allocated array or you could use a std::vector.

你说的这种情况是不可能的。类总是有一个恒定的大小。您可以让您的类使用指向动态分配数组的指针,或者您可以使用 std::vector。

回答by Adam Rosenfield

No, this is not possible. You should use a dynamic array such as an std::vector. C99 allows a struct to have an unsized array as the lastmember only, but even when you do this you still have to manually allocate the memory yourself, e.g. with malloc().

不,这是不可能的。您应该使用动态数组,例如std::vector. C99 允许一个结构体只有一个未定大小的数组作为最后一个成员,但即使你这样做,你仍然必须自己手动分配内存,例如使用malloc().