I have template Vector(my own template not STL). And i have problem with friend operator*
. The problem is the results are ranodm number not the multiply of integer.
#include <iostream>
#include <limits>
using namespace std;
template<typename T,int Roz>
class Vector{
public:
T tab[Roz];
T get(int i)
{
return tab[i];
}
void set(T val,int i)
{
tab[i]=val;
}
friend Vector operator* (Vector & a, const int & b){
Vector<T,Roz> w;
for(int i=0;i<Roz;++i)
{
cout<<a.get(i)<<" ";
w.set(i,a.get(i)*b);
}
cout<<endl;
for(int i=0;i<Roz;++i)
{
cout<<w.get(i)<<endl;;
}
return w;
}
};
int main()
{
Vector<int,6> w;
w.set(2,0);
w.set(3,1);
w.set(5,2);
w.set(5,3);
w.set(5,4);
w.set(5,5);
cout<<w.get(0)<<" "<<w.get(1)<<" "<<w.get(2)<<" "<<w.get(3)<<" "<<w.get(4)<<" "<<w.get(5)<<endl;
Vector<int,6> zz=w*3;
cout<<w.get(0)<<" "<<w.get(1)<<" "<<w.get(2)<<" "<<w.get(3)<<" "<<w.get(4)<<" "<<w.get(5)<<endl;
cout<<w.get(0)<<" "<<w.get(1)<<" "<<w.get(2)<<" "<<w.get(3)<<" "<<w.get(4)<<" "<<w.get(5)<<endl;
cout<<zz.get(0)<<" "<<zz.get(1)<<" "<<zz.get(2)<<" "<<zz.get(3)<<" "<<zz.get(4)<<" "<<zz.get(5)<<endl;
return 0;
}
For code beyond the output values are:
2 3 5 5 5 5 5
2 3 1 5 5 5 5 <----- one insted of five!! Is the same vector after multiply!
8 <---------- 2*3 is not 8
1976963470
1976963426 <--------n/c
2
0
0
2 3 1 5 5 5
2 3 1 5 5 5
8 1976963470 1976963426 2 0 0
The results are random numers not vectors. Where is my mistake?
You are doing:
w.set(i, a.get(i) * b)
So you're passing the index as the first argument, and the value as the second argument. But your function set()
is declared as:
void set(T val, int i)
Where the first argument is the value and the second argument is the position. It looks like you're swapping the arguments.