【发布时间】:2015-02-20 04:38:25
【问题描述】:
我正在使用 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() 方法以接受 bool 参数:
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 ... );
使用模板参数编译类外方法。
这些应该放在全局范围内。
【问题讨论】:
-
请提供一个完整但最小的例子供读者试用。
-
这不是错误的行为,类模板的成员函数只有在你使用它们时才会被实例化。如果要强制实例化,则通过在 main.cpp 的全局范围内添加行
template class Matrix<int>;来显式实例化Matrix<int>。那么即使没有otherMatrix = matrix;赋值,你的代码也不会编译。 -
看起来很像this question,基本上只有你尝试使用它才会失败。
-
@Praetorian 谢谢!这揭示了类方法实现中的几个错误。我还重载了输入/输出运算符,但它们在类的“外部”并且仍然没有得到检查。 :( 我想我必须手动使用它们来编译它们。
-
@BradleyOdell 你也可以对函数模板做同样的事情,比如
template std::ostream& operator<<<int>(std::ostream&, Matrix<int> const&);
标签: c++ visual-studio compiler-errors