Tod*_*hev 1 c++ arrays constructor
我老老实实地坚持如何在构造函数的调用期间分配数组的大小.另外,我希望数组是'const'.在构造函数中这可能吗?或者我必须做一些更棘手的事情?以下是代码的一部分:
class CustomBitmap
{
public:
CustomBitmap(int width,int height);
~CustomBitmap(void);
private:
const int m_width;
const int m_height;
char const m_components[];
};
Run Code Online (Sandbox Code Playgroud)
////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ///////////////
#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) {}
Run Code Online (Sandbox Code Playgroud)
数组具有固定大小(至少在标准C++中),因此您无法在运行时为其指定大小,但必须在编译时指定其大小.
如果你想要一个可变大小std::vector,在你的情况下使用a
std::vector<char> m_components;
Run Code Online (Sandbox Code Playgroud)
如果向量是const,那么你将无法改变/追加它,所以我真的没有看到它的重点const,除非你在类(C++ 11)中将它简单地初始化为例如
const std::vector<char> m_components(10, 'a'); // const char vector of 10 a's
Run Code Online (Sandbox Code Playgroud)
要么
const std::vector<char> m_components = {'a','b','c'}; // again C++11 in class initialization
Run Code Online (Sandbox Code Playgroud)
你也可以做点什么
template<int N>
class CustomBitmap
{
...
char m_compontents[N];
}
Run Code Online (Sandbox Code Playgroud)
但同样,这是一个模板类,您必须N在编译时指定模板参数,即将其实例化为例如
CustomBitmap<5> my_custom_bitmap; // now m_components has size 5
Run Code Online (Sandbox Code Playgroud)