2017-04-21 51 views
1

我对C++很陌生,来自Python背景。基本上,我想要一个“状态”对象的集合,每个对象都应该有自己的“分布”对象。不同的州可以有不同的分布类型(统一的,正常的等)。我希望能够评估一些观察传递给一个国家的概率,而不用担心该国的分布情况。对我而言,这就是多态性的作用。但是,如果我为观察计算PDF,然后更改其中一个分布参数(即平均值),那么我仍然可以从PDF函数调用中获得相同的答案。很明显,我不了解范围,更新等问题。我会非常感谢解释。我制作了一段缩短的代码片段,希望能够描述我的问题。当我看到类似的问题时,我找不到任何能够回答我的问题的东西 - 不过,如果这是重复发布的话,真诚的道歉。C++函数多态 - 意想不到的行为

#include <iostream> 
#include <math.h> 

class Distribution{ 
/*polymorphic class for probability distributions */ 
    protected: 
     Distribution(double, double); 
    public: 
     double param1, param2; 
     virtual double pdf(double) = 0; 
}; 

class NormalDistribution: public Distribution { 
/*derived class for a normal distribution */ 

    public: 
     NormalDistribution(double, double); 
     double param1, param2; 
     double pdf(double x){ 
      return (1.0/sqrt(2.0*pow(param2, 2.0)*M_PI))*exp(-pow(x - param1 , 2.0)/(2.0*pow(param2, 2.0))); 
     } 
}; 

Distribution::Distribution(double x, double y){ 
    param1 = x; 
    param2 = y; 
} 

NormalDistribution::NormalDistribution(double x, double y): Distribution(x, y) { 
    param1 = x; 
    param2 = y; 
} 

class State { 
    /*simple class for a state object that houses a state's distribution */ 
    public: 
      Distribution *dist; 
     State(Distribution * x){ 
      dist = x; 
     }; 
}; 

class myBoringClass{ 
    public: 
     int x; 
     int myBoringFunction(int y){ 
      return x*y; 
     } 
}; 

int main(){ 

    //For polymorphic NormalDistribution class 
    NormalDistribution nd2(0.0,1.0); 
    NormalDistribution *np = &nd2; 
    State myState(np); 

    //Set an initial mean, std and evaluate the probability density function (PDF) at x=0.5 
    std::cout << "PDF evaluated at x=0.5, which should be 0.352: " << myState.dist -> pdf(0.5) << std::endl; //this gives the right answer, which is 0.352 

    //Now change the mean and evaluate the PDF again 
    myState.dist -> param1 = 2.0; 
    std::cout << "PDF evaluated at x=0.5, which should be 0.1295: "<< myState.dist -> pdf(0.5) << std::endl; //this gives the wrong answer. Should give 0.1295, but instead gives 0.352. 

    //For myBoringClass, which works as I would expect 
    myBoringClass boringClass; 
    boringClass.x = 4; 
    std::cout << "Should be 2*4: " << boringClass.myBoringFunction(2) << std::endl; //prints 8 
    boringClass.x = 5; 
    std::cout << "Should be 2*5: " << boringClass.myBoringFunction(2) << std::endl; //prints 10 

    return 0; 
} 

回答

4

你必须与基(Distribution)和派生(NormalDistribution)类的同名成员变量。从NormalDistribution中删除double param1, param2;

+0

这样做的伎俩,非常感谢你! – simpleton