向量不取我给出的值

Vector doesnt take the value I give

本文关键字:向量      更新时间:2023-10-16

感谢您的帮助!问题是,当我运行程序并给出向量的维度时,它需要另一个大整数或负值。正如你所看到的,我使用模板,这是第一次,所以也许这就是问题所在。这是代码,谢谢!

#include <cstdlib>
#include <iostream>
#include <cstring>
#include <new>
using namespace std;
template <class Tipo>
class Vector
{
   friend ostream& operator<<(ostream & COUT,const Vector<Tipo> &W)
   {
       COUT << '(';
       for(int i = 0;i < W.dim ;i++) COUT << W.V[i] << ',';
       COUT<<"b)";
       return COUT;
   }
   friend istream& operator>>(istream & CIN,Vector<Tipo> &W)
   {
       for(int i = 0;i < W.dim ;i++){
           cout<<"Ingrese la componente " << i + 1<< " del vector." << endl;
           CIN>>*(W.V+i); // W.V[i]
       }  
       return CIN;
   }
   friend Vector operator*(Tipo esc, const Vector<Tipo> &W)
   {
       return W*esc;
   }
public:
    explicit Vector(int dim)
    {
        if(dim>0){
                V = new (nothrow) Tipo[dim];
            for(int i=0;i<dim;++i) V[i]=0;
        } 
    }
     Vector(const Vector<Tipo> &W)
     {
        dim=W.dim;
        if(dim){
            V=new (nothrow) Tipo[dim];
            for(int i=0;i<dim;++i) V[i]=W.V[i];  
        }
    }
    ~Vector()
    {
        if(V){
                dim=0;
                delete [] V;
        }
    }
    Vector operator+(const Vector<Tipo> &W) const
    {
        Vector S(dim);
        for(int i = 0;i < dim;i++){
            S.V[i] = V[i] + W.V[i];
        }
        return S;
    }
    private:
        Tipo *V;
        int dim;
    };
int main()
{
    int dim;
    float pEscalar, numEscalar;
    cout << "Programa que calcula la suma de dos vectores en R^n, n>0" << endl;
    do
    {
        cout << "n: ";
        cin >> dim;
    }while(dim <= 0);
    Vector<float> V(dim) ,W(dim),S(dim),R(dim);
    cout<<"Primer vector..." << endl;
    cin>>V;
    cout<< endl << endl << "Segundo vector..." << endl;
    cin>>W;
    S=V+W;  
    cout << endl << "La suma del primer y segundo vector es: " << endl;     
    cout<<V<<" + "<<W<<" = "<<S<<endl;
    cout << endl;    
    system("pause");
    return EXIT_SUCCESS;
}

看看你的 Vector 构造函数,它有一个 int 参数:

    explicit Vector(int dim)
    {
        if (dim>0){
            V = new (nothrow) Tipo[dim];
          for(int i=0;i<dim;++i) V[i]=0;
        } 
    }
   // So where do you assign the dim value in your object??

将 dim 分配给对象的位置? 这是你想做的,以解决你的直接问题,但我还要声明你的班级还有其他问题需要另一个讨论线程。

    explicit Vector(int dim_) : dim(dim_)
    {
        if (dim>0){
            V = new (nothrow) Tipo[dim];
          for(int i=0;i<dim;++i) V[i]=0;
        } 
    }

另外,为什么不使用调试器? 如果使用调试器运行代码,则在执行此行后几秒钟内应该会发现问题:

   Vector<float> V(dim) ,W(dim),S(dim),R(dim);

你会看到V.dim,W.dim等是垃圾值。