代码之家  ›  专栏  ›  技术社区  ›  Aku

模板和好友运算符*

  •  -1
  • Aku  · 技术社区  · 12 年前

    我有模板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 回复  |  直到 12 年前
        1
  •  2
  •   Andy Prowl    12 年前

    您正在执行:

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

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

    void set(T val, int i)
    

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