home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!decwrl!bu.edu!wang!news
- From: eeron@techunix.technion.ac.il (Ron Daisy)
- Newsgroups: comp.lang.c++
- Subject: A vector class problem. Help!
- Message-ID: <1992Sep9.100509.26490@discus.technion.ac.il>
- Date: 9 Sep 92 10:05:09 GMT
- Sender: news@wang.com
- Reply-To: eeron@techunix.technion.ac.il (Ron Daisy)
- Organization: Technion, Israel Inst. of Technology
- Lines: 72
-
- I want to have a vector class and to overload operators on it.
- I tryed the following structure:
-
- typedef float VecTerm;
- typedef VecTerm *vec;
- class vector {
- private:
- vec v;
- int dim;
- public:
- vector(int);
- ~vector(void);
- vector operator = (const vector& ) ;
- float& operator[](int) const;
- int size() const;
- vector operator + (const vector& x) const;
- .
- .
- .
- };
-
- The body of the operators is given by:
-
- inline vector::vector(int n)
- {
- assert(n>0);
- v = new VecTerm[n];
- assert( v != 0);
- dim = n;
- }
- vector::~vector(void) {
- delete v;
- }
-
- inline vector vector::operator = (const vector& x)
- {
- assert(dim == x.dim);
- dim = x.dim;
- v = x.v;
- return *this;
- }
-
- inline float& vector::operator[] (int n) const {
- assert( (n >= 0) && (n < this->dim) );
- return *(v + n);
- }
-
- int vector::size(void) const { return dim; }
-
- vector vector::operator + ( const vector& x) const
- {
- int i;
- assert( x.dim == dim );
- vector result(x.dim);
- for (i = 0; i < x.dim; i++)
- {
- result[i] = *(x.v+i) + *(v+i);
- };
- return result;
- };
-
- When i tryed to run it and to use the '+' operator, it behaved very
- strangely. The first two elements of the answer vector were wrong, and the rest
- were OK.
- When i ran a debuger i understood that the reson for this "strange" behavior
- is the destructor. My mistake is the return of local vector (result) which was
- destructed after the operator call was ended. This destruction is critical
- since the returned vector contain a pointer!
-
- Do some one has an idea how can i solve this problem?
-
- Thanx!
-