老实说,我对如何在构造函数调用期间分配数组的大小感到困惑。另外,我希望数组是一个“const”。在构造函数中这可能吗?还是我必须做一些更棘手的事情?以下是部分代码:
class CustomBitmap
{
public:
CustomBitmap(int width,int height);
~CustomBitmap(void);
private:
const int m_width;
const int m_height;
char const m_components[];
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CustomBitmap.h"
CustomBitmap::CustomBitmap(int width,int height) : m_width(width), m_height(height)
// How do I implement the array? none of the syntax works, I tried m_components([width * height *4]) and all sorts of things along that line.
{}
CustomBitmap::~CustomBitmap(void) {}
最佳答案
数组具有固定大小(至少在标准 C++ 中如此),因此您不能在运行时为其分配大小,而必须在编译时指定其大小。
如果你想要可变大小,在你的情况下使用 std::vector
std::vector<char> m_components;
如果 vector 是 const
,那么你将无法更改/附加到它,所以我真的不明白让它成为 const
的意义, 除非你在类 (C++11) 中简单地初始化它,例如
const std::vector<char> m_components(10, 'a'); // const char vector of 10 a's
或
const std::vector<char> m_components = {'a','b','c'}; // again C++11 in class initialization
你也可以做类似的事情
template<int N>
class CustomBitmap
{
...
char m_compontents[N];
}
但同样,这是一个模板类,您必须在编译时为其指定模板参数 N
,即将其实例化为例如
CustomBitmap<5> my_custom_bitmap; // now m_components has size 5
关于c++ - [C++]在构造函数期间为数组分配大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27180653/