Variables printing as nan or inf instead of actual value
我正在开发一个基于距离和速度来计算时间的程序,当我把最后的时间从a点移到b点而不是获得100英里时,我要么nan或inf取决于我的班级设置方式。有人可以帮我吗?
我的课程的一部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Trip { private: string chicago, illinois, destCity, destState; double distance, time, rate; public: Trip() { chicago ="Chicago"; illinois ="Illinois"; destCity =""; destState =""; distance = 0.0; time = 0.0; rate = 0.0; } Trip(string city, string state, double distance) { chicago ="Chicago"; illinois ="Illinois"; destCity = city; destState = state; distance = 0.0; time = 0.0; rate = 0.0; } |
这是构造函数在我的主要方法中的样子:
1 | Trip atlanta("Atlanta","Georgia", 587); |
,然后是一些可能成为问题一部分的变异器方法:
1 2 3 4 5 6 7 8 9 | void Trip::setRate(double mph) { mph = rate; } void Trip::calcTime() { time = distance/rate; } |
现在我是否可以像这样设置班级
1 2 | this->city =""; this->distance = 0.0; |
当我使用accesor方法检索时间,距离等时,其打印为" nan ",但是如果我将班级设置为
1 2 | city =""; distance = 0.0; |
然后我得到" inf "。
当我调试程序时,即使使用构造函数将值传递给类成员之后,跳闸对象也会显示所有变量均为0。我不知道怎么了。
在此功能中:
1 2 3 4 | Trip(string city, string state, double distance) { // ... distance = 0.0; |
最后一行设置功能参数
要解决此问题,您可以编写
1 2 3 4 5 6 | Trip(string city, string state, double distance) : chicago("Chicago") , distance(distance) , // etc. { } |
和/或为参数使用与您为类成员使用的名称不同的名称。
在初始化列表中,
在C 11中,您可以在类定义中设置默认值,这避免了您必须在每个构造函数中重复使用默认值的情况:
1 2 3 4 5 6 7 | class Trip { private: string chicago, illinois, destCity, destState; double distance = 0.0; double time = 0.0; double rate = 0.0; |
请注意,无需将