【发布时间】:2020-11-08 11:47:16
【问题描述】:
我在尝试理解以下内容时遇到了一些麻烦。
在使用 vector 和模板编写一个简单的 Matrix 类时,我尝试重载 [] 运算符以访问元素。这是课
#pragma once
#include <vector>
#include <iostream>
template <typename T>
class Matrix
{
private:
std::vector<std::vector<T>> values;
int rows, cols;
public:
Matrix(int row, int col) : rows(row), cols(col) {
values = std::vector<std::vector<T>>(rows, std::vector<T>(cols));
}
std::vector<T>& operator[] (const int i) const{
return values[i];
}
};
请注意,我返回的是 vector<T>,因此我可以轻松使用双索引。
我遇到的问题是,在尝试调用操作员时,出现以下错误:
Cannot realize the conversion from 'const_Ty' to 'std::vector<T,std::allocator<T>> &
而且我不知道这种转换发生在哪里。我没有修改课堂上的任何内容,所以我认为我应该使用const。
【问题讨论】:
标签: c++