![](/img/trans.png)
[英]How can I have a local variable that persists over time but is not shared among all members of the same class?
[英]how can I design a class with one variable and still work with different variables at the same time?
我有一个代码设计问题。
我建立了一个类,用于分析数据样本。 它考虑一个样本并分析该样本。 例如,它可以计算样本均值和样本方差。 因此,其最基本的形式在头文件中如下所示:
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;
};
现在,我想编写一个函数calcCovariance
,它可以计算两个样本之间的协方差。 其定义如下所示:
double calcCovariance(vector<double> &s1, vector<double> &s2);
但是,该类仅包含一个称为sample
私有变量。 如何最好地设计类层次结构,使我的类仅包含一个变量sample
,并且仍然可以同时处理多个样本?
提前致谢。
把类的功能外(我不认为需要以下的讨论:-)),如果Statistics
由于某种原因需要类,提供了一个访问到sample
如
namespace utilitystuff
{
double calcCovariance(const vector<double> &s1, const vector<double> &s2)
{
//definition
}
}
样本访问器:
const vector<double>& Statistics::getSample{return sample;}
并这样称呼它:
//Assuming we have Statistics objects stats1 and stats2.
double covariance = utilitystuff::calcCovariance(stats1.getSample(), stats2.getSample());
定义你的类是这样的:
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;
};
并实现类似:
double Statistic::calcCovariance(const Statistic &other) const
{
// TODO: use other.sample and sample here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.