-1

我有模板向量(我自己的模板不是 STL)。我有问题friend operator*。问题是结果是随机数而不是整数的乘积。

#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

结果是随机数而不是向量。我的错误在哪里?

4

1 回答 1

2

你正在做:

w.set(i, a.get(i) * b)

因此,您将索引作为第一个参数传递,将值作为第二个参数传递。但是您的函数set()声明为:

void set(T val, int i)

其中第一个参数是值,第二个参数是位置。看起来你正在交换论点。

于 2013-04-13T17:24:33.700 回答