【发布时间】:2016-04-02 23:11:24
【问题描述】:
我有一个带有行和列的稀疏矩阵类。行整数用于初始化动态数组中的多个 LinkedList。
template<class T>
SM<T>::SM(int rows, int columns)
{
this->rows = rows;
this->columns = columns;
this->rowList = new LinkedList<T>[rows];
cout << "Going to create a sparse matrix of dimensions " << this->rows << "-" << this->columns << endl;
}
我也有这个复制构造函数供以后使用:
编辑:
LinkedList 拷贝构造函数:
LinkedList(const LinkedList & other) {
this->size = other.size;
this->head = NULL;
this->tail = NULL;
NodeType<T> * current = other.head;
while (current != NULL) {
setValue(current->info, current->index);
current = current->link;
}
}
SparseMatrix 复制构造函数:
template<class T>
SM<T>::SM(const SM<T> & other)
{
this->rows = other.rows;
this->columns = other.columns;
this->rowList = new LinkedList<T>[this->rows];
for (int i = 0; i < this->rows; i++)
{
rowList[i] = other.rowList[i];
}
}
这是我的 LinkedList 析构函数和 SparseMatrix 析构函数:
~LinkedList() {
cout << "Going to delete all " << size << " elements of the list." << endl;
NodeType<T> * current = head;
while (current != NULL) {
current = current->link;
delete head;
head = current;
}
}
template<class T>
SM<T>::~SM()
{
cout << "Deleting sm" << endl;
delete [] rowList;
rowList = NULL;
}
但是,当我完成代码时。我得到一个析构函数错误。
这是我的 main() :
SM<int> sm(rows, columns);
SM<int> sm2(rows, columns);
SM<int> sm3 = sm2;
这是错误:
_CrtIsValidHeapPointer
我是 C++ 新手,我真的不知道我的代码有什么问题。任何帮助都深表感谢。
【问题讨论】:
-
您是否为
LinkedList<T>实现了有效的复制赋值运算符? -
您正在调用函数
readElements和printMatrix。如果这些函数对问题没有影响,请删除它们并重新运行您的代码。否则,发布这些函数。 -
另外,
LinkedList的析构函数是做什么的?如果它还遍历链接(因此删除一个也会删除所有链接的节点),那么您不应该在SM的析构函数中明确地这样做。删除一个对象两次会产生未定义的行为。 -
让我们看看您的
LinkedList用户定义的复制构造函数和赋值运算符。这条线最好有一个赋值运算符才能正常工作:rowList[i] = other.rowList[i]; -
@Kelok Chan 你应该分享一个简短的、独立的、正确的(可编译的)程序,这将使你很容易理解你面临的问题。
标签: c++ constructor destructor copy-constructor