Is it possible to make a generic function with multiple parameters a friend in a class in c++?

时间:2016-02-12 20:13:45

标签: c++ templates friend

I'm want to make the function operator+ a friend of class Matrix.

I could use the function as is but I want to know if this is possible. I've tried several ways but all resulted in linker errors and the program didn't compile.

I'm currently learning C++ and here's my code:

#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();

}

1 个答案:

答案 0 :(得分:0)

The simplest is to define it inside the class:

complex types