【发布时间】:2020-04-12 11:12:44
【问题描述】:
我正在编写实现矩阵的某些功能的作业。为了解决这个问题,这里有一个简化版本。
#include <iostream>
using namespace std;
template<class T>
class CMyMatrix{
private:
int row;
int col;
T** elements;
public:
CMyMatrix(int row, int col);
void SetMatrix(T* data, int row, int col);
friend void DisplayMatrix(CMyMatrix<T> matrix);
};
template<class T>
CMyMatrix<T>::CMyMatrix(int row,int col) {
this->row = row;
this->col = col;
this->elements = new T* [row];
for (int i = 0;i < row;i++) {
this->elements[i] = new T[col];
}
}
template<class T>
void CMyMatrix<T>::SetMatrix(T* data, int row, int col) {
this->row = row;
this->col = col;
if (elements != 0) delete[]elements;
this->elements = new T* [row];
for (int i = 0;i < row;i++) {
this->elements[i] = new T[col];
}
for (int i = 0;i < row * col;i++) {
elements[i / col][i % col] = data[i];
}
}
template<class T>
void DisplayMatrix(CMyMatrix<T> matrix) {
for (int i = 0;i < matrix.row;i++) {
for (int j = 0;j < matrix.col;j++) {
cout << matrix.elements[i][j] << " ";
if (j == matrix.col - 1) {
cout << endl;
}
}
}
}
int main(){
CMyMatrix<int> matrix(2, 3);
int a[6] = {1, 2, 3, 4, 5, 6};
matrix.SetMatrix(a, 2, 3);
DisplayMatrix(matrix);
return 0;
}
我们的老师说我们必须让“DisplayMatrix”成为一个全局函数,所以它必须是 CMyMatrix 类的友元函数(如果我不想写更多函数的话)。但也有这样的例外。
代码:LNK2019;说明:函数_main中引用的未解析外部符号“void _cdecl DisplayMatrix(class CMyMatrix)”(?DisplayMatrix@@YAXV?$CMyMatrix@H@@@Z); 1号线;
文件:CMyMatrix.obj
我注意到 CMyMatrix 类中的“DisplayMatrix”在我的 IDE 中不会改变颜色,所以我认为可能存在一些问题。但我不知道如何解决它。如果有人可以帮助我,我将不胜感激。
【问题讨论】: