本文介绍了Monte Carlol模拟的C ++类设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个蒙特卡罗对象类,我想知道设计相关类的最好方法。

I'm trying to build a Monte Carlo object class and am wondering about the best way to design the relevant classes.

对象的结构)包含名称,描述 AND分布类型,其可以是几种不同类型,例如。正常,固定整数,三角形等。
Distribution类是(或可能是)特定分布的超类。正常。

The structure of the object (called Entity) contains name, description AND a Distribution type which can be of a few different types eg. Normal, Fixed Integer, Triangle etc.The Distribution class is (or might be) a superclass of the specific distributions eg. Normal.

所以,我有

class Entity {
public:
  string name;
  Distribution* dsn; // superclass. Can this be done?
}

class Distribution {
   public:
   string Type;
   double Sample(void)=0; // To be implemented in subclasses, same function sig.
}

然后,实际分配的示例可能是

Then an example of the actual distribution might be

class NormalDistribution : public Distribution {
    public:
    setMean(double mean);
    setStdDeb(double stddev);
    double Sample(void);
}

FixedDistribtion也将是Distribution的子类并实现不同的方法。 setWeights,setValues以及Sample of Sample。

FixedDistribtion would also be a subclass of Distribution and implement different methods eg. setWeights, setValues as well as Sample of course.

我希望这样编写代码

Entity* salesVolume = new Entity();
salesVolume->setDistribution(NORM);
salesVolume->dsn->setMean(3000.0:
salesVolume->dsn->setStdDev(500.0);

Entity* unitCost = new Entity();
unitCost->dsn->setWeights( .. vector of weights);
unitCost->dsn->setValues( .. vector of values) ;

然后

loop
   sv = salesVolume->sample();
   uc = unitCost->sample();
endloop

我想要做的是在Entity中定义一个Distribution(超类),然后使用它的子类方法,该方法根据分布类型而变化,例如setMean。Entity中的分布对象将被确定运行时例如
if(distnType == NORM)dsn = new NormalDistribution;
if(distnType == FIXED)dsn = new FixedDistribution;

What I'd like to do is define a Distribution (superclass) in Entity, then use its subclass methods which vary depending on distribution type eg. setMean. The distribution object in Entity would be determined at run-time eg.if (distnType == NORM) dsn = new NormalDistribution;if (distnType == FIXED) dsn = new FixedDistribution;

在C ++中是可能的,还是完全失去了多态性的概念?我无法将dsn变量定义为超类,然后在运行时缩小到实际的分布。一个(更简单的)方式是定义实体而不使用分布,并使用自己的分布,而不附加到实体。

Is this possible in C++, or have completely lost the concept of Polymorphism? I'm having trouble defining the dsn variable as the superclass, then narrowing down to an actual distribution at run-time. A (simpler) way would be to define Entity without a Distribution, and use Distribution's on their own, without attachment to Entity.

感谢伙伴

推荐答案

根据pg1989和Robert Cooper的回答发布自己的解决方案。

Posting own solution based on answers by pg1989 and Robert Cooper.

将使用分发,模板。
访问者模式可以用来解决这个问题,需要一个主类的不同实现。

To define different types of Distribution, templates will be used.The visitor pattern can be used to solve this problem of wanting different implementations of a master class.

这篇关于Monte Carlol模拟的C ++类设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:05