行列のいくつかの関数を実装する割り当てを書いています。これは、問題を修正するための簡略化されたバージョンです。
#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で色を変えないことに気付いたので、いくつかの問題があるのではないかと思います。しかし、私はそれを解決する方法がわかりません。誰かが私を助けてくれたら幸いです。
friend
宣言がグローバルスコープで関数テンプレートの定義と一致していない非テンプレート関数を宣言します。
あなたは出来る
// forward declaration
template<class T>
class CMyMatrix;
// declaration
template<class T>
void DisplayMatrix(CMyMatrix<T> matrix);
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 declaration; refering to the function template
friend void DisplayMatrix<T>(CMyMatrix<T> matrix);
// ^^^
};
...
// definition
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;
}
}
}
}
または、テンプレートを次のfriend
ように宣言します
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);
// declares template friend;
// note that all the instantiations of DisplayMatrix become friend
template <class X>
friend void DisplayMatrix(CMyMatrix<X> matrix);
};
...
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;
}
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加