Re: array as member of class
Jim Langston <tazmaster@rocketmail.com> wrote in message...
"Florian B?rzle" <fbuerzle@gmx.de> wrote in message...
Thanks for the quick reply. Can you give me a hint how to implement such
a dynamic array in this case? (Sorry if this is trivial, but I've never
used dynamic arrays).
Pick one. My preference is Foo.
#include <iostream>
#include <vector>
extern const int dim; // dimension of the array
const int dim = 10;
class Foo
{
public:
Foo( const int Size )
{
x.resize( Size );
}
std::vector<double> x;
};
I prefer 'initialization lists':
class Foo{ public:
Foo( size_t const Size ) : x( Size, 3.14 ){} // OP, note the colon
Foo() : x( dim ){} // 'dim' doubles inited to zero (Foo2 below)
std::vector<double> x;
};
/* - main() or ? -
Foo aFoo( 7 );
std::cout<<" aFoo.x.at(2)="<<aFoo.x.at(2)<<std::endl;
// out: aFoo.x.at(2)=3.140000
*/
class Foo2{ public: // shortened to *my* style for NG post
Foo2(){ x.resize( dim ); }
std::vector<double> x;
};
class Bar{ public:
Bar( const int Size ) { x = new double[ Size ]; }
~Bar() { delete[] x; }
double* x;
};
class Bar{ public:
Bar( size_t const Size ) : x( new double[ Size ] ){}
~Bar() { delete[] x; }
double *x;
};
// 'function level try block' for Ctor not shown.
// Why 'size_t' (unsigned integer type)?
class Bar{ public:
// Bar( int const Size ) : x( new double[ Size ] ){}
// use: Bar aBar( -1 ); runtime-error: bad_alloc
Bar( size_t const Size ) : x( new double[ Size ] ){}
// use: Bar aBar( -1 ); compile-warning
// [Warning] passing negative value `-1'
// for argument 1 of `Bar::Bar(unsigned int)'
// == a HUGE size
~Bar(){ delete[] x; }
double *x;
};
[ snip other examples ]
OP: Jim was keeping it simple so not to confuse you. Look over his post
before you tackle the 'init list' modifications I've shown.
The 'initialization lists; are the prefered way to do it, when you can
(sometimes you must use the body of the constructor (like to set init values
in array[])).
More questions? No problem, ask away.
--
Bob R
POVrookie