关于在类模板(C ++)中声明朋友功能模板的问题

问题描述 投票:0回答:1

我正在编写实现矩阵某些功能的作业。这是为了解决此问题的简化版本。

#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中更改颜色,因此我认为可能存在一些问题。但是我不知道如何解决。如果有人可以帮助我,我将不胜感激。

c++ templates friend
1个回答
1
投票

friend声明声明了一个非模板函数,该函数与全局范围内的函数模板的定义不匹配。

您可以

© www.soinside.com 2019 - 2024. All rights reserved.