how can I design a class with one variable and still work with different variables at the same time?

StackOverflow https://stackoverflow.com/questions/20914738

質問

I have a code design question.

I have built a class that is meant to analyze a sample of data. It considers a sample and analyzes the sample. For example, it can compute the sample mean and sample variance. Therefore, in its most rudimentary form it looks like this in the header file:

class Statistic{
public:
    // constructors
    Statistic();
    Statistic(vector<double> &s);

    // other functions
    double calcMean(void);
    double calcMean(vector<double> &s);
    double calcVariance(void);

private:
    vector<double> sample;
};

Now I would like to write a function calcCovariance that can compute the covariance between two samples. Its definition would be something like this:

double calcCovariance(vector<double> &s1, vector<double> &s2);

However, the class only contains one private variable called sample. How can I best design my class hierarchy such that my class only contains one variable sample, and I can still work with several samples at the same time?

Thanks in advance.

役に立ちましたか?

解決

Put the function outside of the class (which I don't think is required following the discussion :-) ) and if the Statistics class is for some reason required, provide an accessor to sample e.g.

namespace utilitystuff
{
    double calcCovariance(const vector<double> &s1, const vector<double> &s2)
    {
        //definition
    }
}

Accessor to sample:

const vector<double>& Statistics::getSample{return sample;}

And call it like so:

//Assuming we have Statistics objects stats1 and stats2.
double covariance = utilitystuff::calcCovariance(stats1.getSample(), stats2.getSample());

他のヒント

define you class something like this:

class Statistic{
public:
    // constructors
    Statistic();
    explicit Statistic(vector<double> &s);

    // other functions
    double calcMean(void) const;
    double calcVariance(void) const;

    double calcCovariance(const Statistic &other) const;

private:
    vector<double> sample;
};

and implement something like:

double Statistic::calcCovariance(const Statistic &other) const
{
// TODO: use other.sample and sample here.
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top