首页 > 解决方案 > 构建对象数组是如何工作的?我坚持这个例子

问题描述

我试图理解一些用于 ESP32 EPaper 模块(TTGO T5 V2.2)的代码。该程序使用 Button2 库来处理按下三个按钮之一时的事件。它为每个按钮初始化一个对象并将其存储在一个指针数组中。当我想编译代码时,出现以下错误:

error: no matching function for call to 'Button2::Button2()'

(info: Button2 *pBtns = nullptr; args = 3; ) 发生错误的代码行是:

pBtns = new Button2 [args];

到目前为止,我明白,这条线是否应该为该新对象保留堆上的内存。那么为什么要有一个函数,它的目的是什么?

到目前为止,我尝试使用固定的数组大小并使用互联网上某处找到的一些示例中的片段:

//Button2 pBtns[5] = {nullptr,nullptr,nullptr,nullptr,nullptr};
//Button2 pBtns[5];
//Button2* pBtns = static_cast<Button2*>( ::operator new ( sizeof(Button2) * (sizeof(g_btns) / sizeof(g_btns[0]))));
//  g_btns[] is the array of gpio pins of the buttons

由于缺少示例,我仍然不知道是否遗漏了某些内容,但是如果我没记错的话,“调用没有匹配的函数”错误提示对象本身存在问题...

// in Button2.h:

class Button2 {
  private:
    .// some private defs ...
  public:
    Button2(byte attachTo, byte buttonMode = INPUT_PULLUP, unsigned int debounceTimeout = DEBOUNCE_MS);
    .// some methods here ...
    bool operator==(Button2 &rhs);

    void loop();
};


// in program code:

#define BUTTONS_MAP {37,38,39}

Button2 *pBtns = nullptr;
uint8_t g_btns[] =  BUTTONS_MAP;

void button_init()
{
    uint8_t args = sizeof(g_btns) / sizeof(g_btns[0]);
    pBtns = new Button2 [args];   //<<<<<<< COMPILER-ERROR is HERE
    //pBtns = new Button2;
    for (int i = 0; i < args; ++i) {
        pBtns[i] = Button2(g_btns[i]);
        pBtns[i].setPressedHandler(button_callback);
    }
}

我希望在上面的示例中 pBtns 包含一个数组,其中包含 3 个指向新创建和初始化对象的指针。另外我想知道错误消息中的功能是什么。我喜欢将对象存储在数组中的想法,并希望在我自己的开发中使用它,当我了解原理并实践时 - 那么技术的优缺点是什么?

(长文本的sri - 只是还不知道什么是相关的,所以拉皮条我的大脑!)

标签: c++

解决方案


When an array is allocated, the program will attempt to default construct the elements.

You cannot default construct Button2 because defining another constructor disables the automatically generated default constructor. You need to either add a default constructor or move to a smarter container like std::vector.

Example:

Button2 *pBtns = nullptr;

becomes

std::vector<Button2> btns;

And then later buttons are created in the vector with

btns.emplace_back(<arguments>);

As an added bonus, vector removes all of the memory management work that a dynamically allocated array saddles you with.


推荐阅读