gpt4 book ai didi

c++ - 为什么我得到一个 "no instance of constructor matches the MyArray::MyArray"参数列表?

转载 作者:行者123 更新时间:2023-12-01 14:43:46 25 4
gpt4 key购买 nike

#include <iostream>
#include <initializer_list>

class MyArray {
int* array;
public:
MyArray(){}
MyArray(std::initializer_list<int>& v) {
array = new int[v.size()];
int index = 0;
for (auto element : v) {
array[index] = element;
index++;
}
}

~MyArray()
{
delete[] array;
}
};

int main() {
MyArray object{ 2,4,2,2 };
}

这是我第一次使用 std::initializer 进行对象列表初始化。我创建了一个使用 MyArray 构造函数初始化的数组。我不知道我哪里错了。我创建了一个与参数列表匹配的对象,即采用初始化列表的构造函数。

最佳答案

i created an object that matches the argument list, ie a constructor that takes an initializer list.

你没有;不完全是。

您创建了一个构造函数,该构造函数接受对 std::initializer_list引用

但以这种方式创建的 [可能] 是无法绑定(bind)到此类引用的临时文件。

通常,您只想按值获取 std::initializer_list。即:删除 &

cppreference's article on std::initializer_list 上有一些例子.

关于c++ - 为什么我得到一个 "no instance of constructor matches the MyArray::MyArray"参数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59482406/

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