c++ - [C++]在构造函数期间为数组分配大小

标签 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[]; 

};

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#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/

相关文章:

c++ - C++ 中 int* 和 int[] 的区别

c++ - 如何在一个 JsonArray 中添加多个 json 字符串?

c++ - 将多个输入存储到数组中

c++ - 库 Png : Png24 To Png32 and Vice-Versa

c++ - 段错误并返回存储在元素中的值?

javascript - 如何让javascript将多维数组转换为字符串?

c - C中的多维字符串数组

java - 如果一个构造函数调用另一个构造函数,该构造函数为对象分配内存

c++ - 继承中调用构造函数的顺序

c++ - 为什么可以在构造函数中使用成员初始化来满足显式构造函数的参数?