为什么这段代码不能返回值为505.5的bpeeffect变量?

Why can this code not return the bpEffect variable with the value 505.5?

本文关键字:bpeeffect 变量 返回值 不能 段代码 代码 为什么      更新时间:2023-10-16

下面代码的预期结果应该是505.5,但它返回的却是3.97541e+70。为什么会出现这种情况?如何解决这个问题?

#include <iostream>
#include <string>
using namespace std;
class Position {
public:
    Position(int s, double p, string n) {
        shares = s;
        price = p;
        name = n;
    }
    double getBpEffect() {
        return bpEffect;
    }
private:
    string name;
    int shares;
    double price;
    double bpEffect = (shares*price) / 2;
};

int main() {
    Position xyz = Position(100, 10.11, "xyz");
    double buyingPower = xyz.getBpEffect();

    cout << buyingPower;
    system("pause");
    return 0;
}

double bpEffect = (shares*price) / 2;在构造函数体之前使用sharesprice中未定义的值运行。您需要在初始化其他变量之后计算bpEffect

所示的类由构造函数代码和显式成员初始化混合初始化。

除非完全了解类构造的各个部分发生的顺序,否则很容易使事情以错误的顺序发生。

最好的做法是在一个地方初始化所有内容,消除所有歧义:

Position(int s, double p, string n)
   : name(n), shares(s), price(p),
     bpEffect((shares*price) / 2)
{
}