gpt4 book ai didi

c++ - 为类数组成员调用非默认构造函数

转载 作者:行者123 更新时间:2023-11-28 02:11:50 24 4
gpt4 key购买 nike

我的类中有一个名为 items 的数组。创建类型为 MyClass 的对象时,我需要调用参数化构造函数 Member(int value)。如何做到这一点?

class Member
{
public:
Member();
Member(int value)
{
dummy = value * 2;
}
~Member();

private:
int dummy;
}

class MyClass
{
public:
MyClass();
~MyClass();

private:
Member items[10];
}

更新:我现在正在使用单个元素而不是数组来调试更简单的情况。或许你看到更多:为什么这样行得通

user_menu_view::user_menu_view() :
button_clicked_callback(this, &user_menu_view::button_clicked),
on_touch_button_item_selected(this, &user_menu_view::touch_button_item_selected),
users_items(menu_item_common::BACKG_LONG)
{
users_items.set_back_color((uint16_t)0x1951);
users_items.set_menu_item_selected_callback(on_touch_button_item_selected);
meniu_list.add(users_items);
}

这不是:

user_menu_view::user_menu_view() :
button_clicked_callback(this, &user_menu_view::button_clicked),
on_touch_button_item_selected(this, &user_menu_view::touch_button_item_selected)//,
//users_items(menu_item_common::BACKG_LONG)
{
users_items = menu_item_touch_button::menu_item_touch_button(menu_item_common::BACKG_LONG);
// Also, here destructor routine is called. WHy???
users_items.set_back_color((uint16_t)0x1951);
users_items.set_menu_item_selected_callback(on_touch_button_item_selected);
meniu_list.add(users_items);
}

最佳答案

你可以初始化一个数组:

#include <iostream>
#include <array>

struct Element
{
Element() : _value(0) {}
Element(int value) : _value(value) {}
int _value;
};

class Container
{
std::array<Element, 10> _elements; // Element _elements[10]; works too
public:
Container()
: _elements({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
{}

int at(size_t index) { return _elements[index]._value; }
};

int main()
{
Container cont;
std::cout << cont.at(5) << std::endl;
}

按预期打印 6

关于c++ - 为类数组成员调用非默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com