C ++函数多态性 - 意外行为

时间:2017-04-21 15:22:42

标签: c++

我是C ++的新手,来自Python背景。基本上,我想要一个“状态”对象的集合,每个对象都应该有自己的“分布”对象。不同的状态可以具有不同类型的分布(统​​一,正常等)。我希望能够评估一些观察传递到一个州的可能性,而不必担心该州的分布是什么。我发现这就是多态性的含义。但是,如果我为观察计算PDF,然后更改其中一个分布参数(比如平均值),那么我仍然可以从PDF函数调用中得到相同的答案。显然,我不理解范围,更新等问题;我会非常感谢你的解释。我已经制作了一个缩短的代码片段,我希望能够描述我的问题。虽然我找到了类似的问题,但我找不到任何能够回答我问题的内容 - 尽管如此,如果这是一个重复的帖子,真诚的道歉。

#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;
}

1 个答案:

答案 0 :(得分:4)

您在基础(Distribution)和派生(NormalDistribution)类中具有相同名称的成员变量。从double param1, param2;

中删除NormalDistribution