My code doesnt compile and I'm really confused.When I run the code I get an error in the header file that says "Declaration of 'T' shadows template parameter. My teacher told us in class to put template prefix template before declaration of the operators inside a class definition. I don't know if she's wrong or not but I tried removing the template that were above the declaration of friend functions and when i tried compiling the code i get some errors that have linker Id issues. One of them refers to Matrix::Matrix(int). Honestly I still think what my teacher said about putting the template prefix above the declaration of the operator is right because the operators have the class type in their parameter but can someone help me out!
In my header file I have:
#ifndef __testing_more_stuff__vector__
#define __testing_more_stuff__vector__
#include<iostream>
#include<fstream>
using namespace std;
template <class T>
class Matrix{
public:
Matrix();
Matrix(T diagonal);
//template <class T>
friend ostream& operator <<(ostream& outs, const Matrix<T> &obj);
//template <class T>
friend istream& operator >>(istream& in, Matrix<T> &obj);
//template <class T>
friend Matrix<T> operator *(Matrix<T> A, Matrix<T> B);
private:
const static int n=3;
T a[n][n];
};//class declaration
#endif
In my implementation file I have:
#include "vector.h"
template <class T>
Matrix<T>::Matrix(){
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
a[i][j]=0;
}
template <class T>
Matrix<T>::Matrix(T diagonal){
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
if (i==j)
a[i][j]=diagonal;
else
a[i][j]=0;
}
template <class T>
ostream& operator <<(ostream& outs, const Matrix<T> & obj)
{
for (int i = 0; i < obj.n; i++){
for (int j = 0; j < obj.n; j++)
outs << " "<< obj.a[i][j];
outs<<endl;
}
outs<<endl;
return outs;
}
template <class T>
istream& operator >>(istream& in, Matrix<T> & obj)
{
for (int i = 0; i < obj.n; i++){
for (int j = 0; j < obj.n; j++){
in >> obj.a[i][j];
}
}
return in;
}
template<class T>
Matrix<T> operator *(Matrix<T> A, Matrix<T> B){
Matrix<T> product;
for (int i=0;i<A.n; i++)
for (int j=0;j<A.n; j++) {
T sum=0;
for (int k=0; k<A.n; k++)
sum = sum+A.a[i][k]*B.a[k][j];
product.a[i][j]=sum;
}
return product;
}
In my main file I have:
#include "vector.h"
int main(){
Matrix<int> A;
Matrix<int> B(2);
cout << A;
cout <<B;
cout <<"stop here";
ifstream fin;
ofstream fout;
fout.open("output.txt");
if (fout.fail()){
cout <<"error openning output file";
exit(1);
}
fin.open("input.txt");
if (fin.fail()){
cout <<"error openning input file";
exit(1);
}
//input matrix C
Matrix<int> C;
cin >>C;
//fin >>C;
cout <<"C = "<<endl<<C<<endl;
cout <<"B = "<<endl<<B<<endl;
cout <<"C*B = "<<endl<<C*B<<endl;
//fout <<C;
//cout <<C.det();
return 0;
}