模板和朋友操作员*

时间:2013-04-13 17:20:54

标签: c++ templates operators friend

我有模板Vector(我自己的模板不是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

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

1 个答案:

答案 0 :(得分:2)

你在做:

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

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

void set(T val, int i)

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