我正在尝试制作一个 2D 矩阵类,它实际上是 vector 的 vector ,并且两个类都是模板。我在 vector 类中重载了下标运算符。当我尝试使用错误消息重载 matrix 类中的 operator[] 时出现问题: 错误 C2440:“return”:无法从“vector”转换为“vector &”。 这是我类(class)中的代码:
template <typename t>
class vector
{
private:
t *Mem;
int vectsize;
public:
vector<t> (int _vectsize = 0);
//some other methods here
t& operator[](int index)
{
return Mem[index];
}
};
和
template <typename h>
class matrix
{
private:
int dim;
vector< vector<h> > *Mat;
public:
matrix<h> (int _dim = 0);
matrix<h> (const matrix & _copy);
vector<h>& operator[](int index)
{
return Mat[index]; //Here's the error
}
};
我进行了一些谷歌搜索,发现了相同的示例或重载 () 而不是 []。我只是不明白为什么编译器不能将返回值 Mat[index] 视为引用(我相信这一定是引用)。当使用单个 vector 时,下标运算符工作得很好。请指出我的错误。提前致谢!
补充:使用非动态 vector 似乎解决了当前的问题,但我没有遇到类型不匹配的情况,而是遇到了两个链接器错误(未解析的外部符号)。通过注释和反注释我的代码,我发现只有在行 vector< vector<h> > Mat;
时才会出现问题。或 Extend
函数存在(它是类 vector 中的一个空方法)。我想这与 vector 构造函数有关,但我不知道到底出了什么问题。
template <typename t> //vector constructor
vector<t>::vector(int _vectsize)
{
vectsize = _vectsize;
Mem = new t[vectsize];
for (int i=0; i<vectsize; i++)
Mem[i] = 0;
}
在 matrix.h 中(它还没有在单独的文件中):
matrix<h> (int _dim = 0) : Mat(_dim)
{
dim = _dim;
for (int i=0; i<dim; i++)
Mat[i].Extend(dim-i);
}
如果可能的话,我很想听听任何建议。
最佳答案
Mat
是指向 vector 的指针。没有理由动态分配 vector ,只需使用 vector<vector<H>> Mat;
.
此外,operator[]
通常有两种重载:一种用于读取 const,一种用于写入 non-const:
//Read overload
const T& operator[](std::size_t index) const
{
return /* blah blah */
}
//Write overload
T& operator[](std::size_t index)
{
return /* blah blah */
}
这允许在 const 上下文中读取 vector 。
关于C++ 双下标重载 : cannot convert from 'type' to 'type &' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209910/