gpt4 book ai didi

c++ - 二进制 '[' : no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion)

转载 作者:行者123 更新时间:2023-12-03 12:48:32 26 4
gpt4 key购买 nike

尝试编译代码时出现错误:

error C2679: binary '[': no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion). 
note: could be 'double &Matrix<double>::operator [](const std::array<int,2> &)'.
note: while trying to match the argument list '(Matrix<double>, initializer list)'.

我不明白我做错了什么。所以我的问题是出了什么问题以及如何解决它。另外,分配是使用

Matrix<double> M(10, 20);
M[{0, 0}] = 1.0; // set value at row 0, column 0 to 1.0

所以这部分我无法更改。

#include "stdafx.h"
#include <iostream>
#include <initializer_list>
#include <memory>
#include <string>
#include <map>


//Matrix Class
template<typename T>
class Matrix {
private:
int rows;
int columns;
public:
std::map< std::array<int, 2>, T > data;
//Constructor
Matrix() {
rows = 0;
columns = 0;
}

Matrix(int rows, int columns)
: rows(rows), columns(columns)
{
//std::clog << "Matrix(int rows, int columns) called" << std::endl;
}


//Destructor
~Matrix()
{
data.clear();
rows = 0;
columns = 0;
}


T& operator[](const std::array<int, 2>& a) {
return data[a];
}
};


int main()
{
Matrix<double> M(10, 20);
M[{0, 0}] = 1.0; // set value at row 0, column 0 to 1.0
//M[{1, 2}] = 2.0; // set value at row 1, column 2 to 2.0


std::cout << " Finished!" << M[{0, 0}] << std::endl;


return 0;
}

最佳答案

在文件顶部,在#include "stdafx.h" 后面放置

#include <array>

或者,您可以将该行放入文件 stdafx.h 中。

一般来说,每当您看到一条错误消息指出缺少某些内容时,请查看是否存在所有必需的包含文件。该消息可能是“找不到运算符”、“未定义的类”或“不完整的类型”或其他内容。

关于c++ - 二进制 '[' : no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758042/

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