二进制'[':找不到哪个运算符采用'初始化列表'类型的右手操作数(或者没有可接受的转换)

时间:2018-04-10 15:54:12

标签: c++ matrix operators operands

在尝试编译我的代码时遇到错误:

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;
}

1 个答案:

答案 0 :(得分:0)

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

之后
#include <array>

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

通常,每当您看到错误消息表明缺少某些内容时,请查看是否存在所有必需的包含文件。消息可能是“找不到操作员”,“未定义类”或“不完整类型”或其他内容。