Complicated class member construction
Since I know that it is generally much nicer to initialize all members in
the initializer list of the constructor, I would like to know if it is
also possible to do some more complicated construction in c++ inside the
initializer list. In my program I would like to construct a class that
initializes two of it's member vectors. Since I'm using them a Lot I would
like to cache the contents, therefore I want to create the vectors at
construction.
edit The main reason I want to cache these values that I can generate the
the x and y coordinates from a circle with any radius without the need to
recompute the sin and cosine values. So I'm using n (n_samples) for the
granularity of sinx and cosy vector, which I use as lookup table
internally.
So is it possible to do the initialization inside the initializer list, in
such way that the constructor only needs to know how many samples it
should create?
Please note: While writing a short self contained question I wrote sinx
and cosy for the vectors with respectively x and y coordinates of a
circle. I could change this but then I would invalidate answers below. The
sinus of angle gives a y-coordinate and the cosine will give a x value
typically.
#include <vector>
#include <iostream>
#include <cmath>
class circular {
public:
circular( unsigned n = 20 );
/* In my actual program I do much more
* complicated stuff. And I don't want
* the user of this class to be bothered
* with polar coordinates.
*/
void print_coordinates( std::ostream& stream, double radius );
private:
unsigned number_of_samples;
std::vector<double> sinx;
std::vector<double> cosy;
};
circular::circular( unsigned n )
:
number_of_samples(n) //I would like to initialize sinx cosy here.
{
for ( unsigned i = 0; i < number_of_samples; ++i ){
sinx.push_back( std::sin( 2*M_PI / number_of_samples*i ) );
cosy.push_back( std::cos( 2*M_PI / number_of_samples*i ) );
}
}
void
circular::print_coordinates( std::ostream& stream, double r)
{
for ( unsigned i = 0; i < sinx.size(); ++i ) {
stream << "{ " <<
sinx[i] * r <<
" , " <<
cosy[i] * r <<
" } " <<
std::endl;
}
}
int main () {
circular c(20);
c.print_coordinates(std::cout, 4);
c.print_coordinates(std::cout, 5);
return 0;
}
many thanks for your effort.
Heteperfan
No comments:
Post a Comment