我是使用Visual Studio Professional 2013的。我遇到了一个相当奇怪的问题。通常人们会发布有关错误的文章,而我在这里发布的是没有错误的情况。
我编写了一个自定义矩阵类(为了完成作业)。 我已覆盖了分配运算符,如下所示:
template<typename T>
Matrix<T>& Matrix<T>::operator=(const Matrix<T> &other) {
if (this != &other) {
if (this->mRows != other.mRows || this->nColumns != other.nColumns) {
deleteMatrixArray();
this->mRows = other.mRows;
this->nColumns = other.nColumns;
newMatrixArray();
} // else reuse the existing array
// copy contents
for (unsigned int i = 0; i < this->mRows; i++) {
for (unsigned int j = 0; j < this->nColumns; j++) {
this->matrix[i][j] = other.matrix[i][j];
}
}
}
return *this;
}
我最近修改了newMatrixArray()方法,使其接受一个布尔参数:
template<typename T>
void Matrix<T>::newMatrixArray(bool init) {
this->matrix = new T*[this->mRows];
for (unsigned int i = 0; i < this->mRows; i++) {
if (init) {
this->matrix[i] = new T[this->nColumns]();
} else {
this->matrix[i] = new T[this->nColumns];
}
}
}
然而,即使是在这种情况下,Visual Studio 仍然可以成功编译... 除非...
#include "Matrix.h"
int main() {
Matrix<int> matrix;
Matrix<int> otherMatrix;
otherMatrix = matrix;
return 0;
}
我编写了一些使用重载赋值运算符的代码。这让我很担心,因为我不知道还有什么其他问题,而 Visual Studio 没有提醒我!
出现了什么情况?
更多信息:
正如您所见,我正在使用模板。所有 Matrix 代码都在 Matrix.h 文件中 - 声明后跟定义。当使用模板时,这是必需的。Matrix 类是我目前项目中唯一的类,除了 main.cpp 文件以外。我已经检查并确保声明和定义匹配。
来源:Praetorian
编辑:(解决方案)
您可以使用:
template class NameOfClass<NameOfType>;
为了针对特定类型编译模板类。
你还可以使用:
template ReturnType NameOfFunction(Args ... );
编译具有模板参数的类外方法。
这些应放置在全局范围内。
Matrix<int>
,添加一行template class Matrix<int>;
。然后,即使没有otherMatrix = matrix;
赋值,您的代码也无法编译。 - Praetoriantemplate std::ostream& operator<<<int>(std::ostream&, Matrix<int> const&);
这样的东西。 - Praetorian