【发布时间】:2014-12-21 06:30:39
【问题描述】:
我是 C++ 的初学者,所以我开始通过编写自己的 Vector 类来进行一些练习。
它存储数组的行数和列数,元素是动态分配的。
template <class T>
class Vector {
private:
unsigned int rows;
unsigned int cols;
T **elements;
public:
Vector(unsigned int, unsigned int);
~Vector();
};
template <class T>
Vector<T>::Vector(unsigned int rows, unsigned int cols) {
this->rows = rows;
this->cols = cols;
this->elements = new T[this->rows];
for (int i = 0; i < this->rows; i++) {
this->elements[i] = new T[this->cols];
}
}
template <class T>
Vector<T>::~Vector() {
};
这里是代码。当我编译它时(我创建一个对象来测试它:Vector<int> test;),我得到错误:"Cannot convert ‘int*’ to ‘int**’ in assignment"。
为什么会出现此错误?我在网上看到了多维动态分配的例子,在:http://www.cplusplus.com/forum/beginner/63/
【问题讨论】:
-
new T[size]返回T*。elements是T**。 -
仔细阅读您指向的参考资料。您在第一个
new表达式中的某处缺少*。 (把那个东西称为向量是一个非常奇怪的选择。向量有一个维度,你正在构建一个矩阵。) -
vector<vector<int>> -
谢谢,马特!我必须更加小心。我很抱歉这个白痴问题。
-
@NeilKirk:除非地点很重要
标签: c++ arrays class templates dynamic-memory-allocation