是否可以在 c++ 中的 class 中使具有多个参数的泛型函数成为朋友?
Is it possible to make a generic function with multiple parameters a friend in a class in c++?
我想让函数 operator+ 成为 class Matrix 的朋友。
我可以按原样使用函数 ,但我想知道这是否可行。我尝试了几种方法,但都导致链接器错误,程序无法编译。
我目前正在学习 C++,这是我的代码:
#include <iostream>
using namespace std;
template <int N, int M, class T>
class Matrix {
public:
T matrix[N][M];
int rows;
int cols;
Matrix() {
rows = N;
cols = M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = 0;
}
}
}
void set(int i, int j, T item) {
matrix[i][j] = item;
}
T operator[](int i) {
return matrix[i];
}
void show() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
};
// I'm trying to declare this function as a friend. In order to keep
// the matrix attribute private.
template<int N, int M, class T>
Matrix<N, M, T> & operator+(Matrix<N, M, T> &l, Matrix<N, M, T> &r) {
Matrix<N, M, T> * pMatrix = new Matrix<N, M, T>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
pMatrix->matrix[i][j] = l.matrix[i][j] + r.matrix[i][j];
}
}
return *pMatrix;
}
int main() {
Matrix<2, 2, int> matrix;
matrix.set(0, 0, 1);
matrix.set(0, 1, 0);
matrix.set(1, 0, 0);
matrix.set(1, 1, 1);
matrix.show();
cout << endl;
matrix = matrix + matrix;
matrix.show();
}
最简单的就是在class里面定义:
template <int N, int M, class T>
class Matrix {
// Matrix code
friend Matrix operator + (const Matrix& lhs, const Matrix& rhs) {
// implementation
}
};
我想让函数 operator+ 成为 class Matrix 的朋友。
我可以按原样使用函数 ,但我想知道这是否可行。我尝试了几种方法,但都导致链接器错误,程序无法编译。
我目前正在学习 C++,这是我的代码:
#include <iostream>
using namespace std;
template <int N, int M, class T>
class Matrix {
public:
T matrix[N][M];
int rows;
int cols;
Matrix() {
rows = N;
cols = M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
matrix[i][j] = 0;
}
}
}
void set(int i, int j, T item) {
matrix[i][j] = item;
}
T operator[](int i) {
return matrix[i];
}
void show() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
};
// I'm trying to declare this function as a friend. In order to keep
// the matrix attribute private.
template<int N, int M, class T>
Matrix<N, M, T> & operator+(Matrix<N, M, T> &l, Matrix<N, M, T> &r) {
Matrix<N, M, T> * pMatrix = new Matrix<N, M, T>();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
pMatrix->matrix[i][j] = l.matrix[i][j] + r.matrix[i][j];
}
}
return *pMatrix;
}
int main() {
Matrix<2, 2, int> matrix;
matrix.set(0, 0, 1);
matrix.set(0, 1, 0);
matrix.set(1, 0, 0);
matrix.set(1, 1, 1);
matrix.show();
cout << endl;
matrix = matrix + matrix;
matrix.show();
}
最简单的就是在class里面定义:
template <int N, int M, class T>
class Matrix {
// Matrix code
friend Matrix operator + (const Matrix& lhs, const Matrix& rhs) {
// implementation
}
};