我是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/
答案 0 :(得分:2)
最大的错误是您错过了*
&#39;在分配指针数组时:
this->elements = new T*[this->rows];
除此之外:
作为起点,请使用以下代码:
template <class T>
class Vector {
public:
unsigned int rows;
unsigned int cols;
T** elements;
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() {
for(int i=0; i<this->rows;++i)
delete[] this->elements[i];
delete[] this->elements;
};
int main()
{
Vector<int> obj(2,2);
obj.elements[0][0] = 1;
obj.elements[0][1] = 2;
obj.elements[1][0] = 3;
obj.elements[1][1] = 4;
std::cout << obj.elements[0][0] << " " << obj.elements[0][1] << std::endl;
std::cout << obj.elements[1][0] << " " << obj.elements[1][1] << std::endl;
return 0;
}