-1
我有模板矢量(我自己的模板不是STL)。我有friend operator*
問題。問題是結果是ranodm數字不是整數的乘積。模板和朋友操作符*
#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;
}
對於超出的輸出值的代碼是:
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
結果是隨機numers不矢量。我的錯誤在哪裏?
呃,真是太遺憾了。無論如何THX我都很困。 – Aku
@Aku:我們都在那裏;)很高興幫助 –