home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13421 < prev    next >
Encoding:
Text File  |  1992-09-09  |  2.0 KB  |  84 lines

  1. Path: sparky!uunet!decwrl!bu.edu!wang!news
  2. From: eeron@techunix.technion.ac.il (Ron Daisy)
  3. Newsgroups: comp.lang.c++
  4. Subject: A vector class problem. Help!
  5. Message-ID: <1992Sep9.100509.26490@discus.technion.ac.il>
  6. Date: 9 Sep 92 10:05:09 GMT
  7. Sender: news@wang.com
  8. Reply-To: eeron@techunix.technion.ac.il (Ron Daisy)
  9. Organization: Technion, Israel Inst. of Technology
  10. Lines: 72
  11.  
  12. I want to have a vector class and to overload operators on it.
  13. I tryed the following structure:
  14.  
  15. typedef float VecTerm;
  16. typedef VecTerm *vec;
  17. class vector {
  18.   private:
  19.     vec v;
  20.     int dim;
  21.   public:
  22.     vector(int);
  23.     ~vector(void);
  24.     vector operator = (const vector& ) ;
  25.     float& operator[](int) const;
  26.     int size() const;
  27.     vector operator + (const vector& x) const;
  28.     .
  29.     .
  30.     .
  31. };
  32.  
  33. The body of the operators is given by:
  34.  
  35.    inline vector::vector(int n)
  36.    {
  37.      assert(n>0);
  38.      v = new VecTerm[n];
  39.      assert( v != 0);
  40.      dim = n;
  41.    }
  42.    vector::~vector(void) {
  43.      delete  v;
  44.    }
  45.  
  46.    inline vector  vector::operator = (const vector& x)
  47.    {
  48.       assert(dim == x.dim);
  49.       dim = x.dim;
  50.       v = x.v;
  51.       return *this;
  52.    }
  53.  
  54.    inline float& vector::operator[] (int n) const {
  55.      assert( (n >= 0) && (n < this->dim) );
  56.      return *(v + n);
  57.    }
  58.  
  59.    int vector::size(void) const { return dim; }
  60.   
  61.    vector vector::operator + ( const vector& x) const
  62.    {
  63.      int i;
  64.      assert( x.dim == dim );
  65.      vector result(x.dim);
  66.      for (i = 0; i < x.dim; i++)
  67.      {
  68.        result[i] = *(x.v+i) + *(v+i);
  69.      };
  70.      return result; 
  71.    };
  72.  
  73.     When i tryed to run it and to use the '+' operator, it behaved very
  74. strangely. The first two elements of the answer vector were wrong, and the rest 
  75. were OK.
  76.    When i ran a debuger i understood that the reson for this "strange" behavior
  77. is the destructor. My mistake is the return of local vector (result) which was
  78. destructed after the operator call was ended. This destruction is critical
  79. since the returned vector contain a pointer!
  80.  
  81. Do some one has an idea how can i solve this problem?
  82.  
  83. Thanx!
  84.