2017-02-27 142 views
-3

嗨,我是一个C++初学者,我真的不能让我的头绕着这个错误 从'double'到'int'的转换需要缩小转换 这是我的码; #include“Segment.h” using namespace imat1206;从'双'转换为'int'需要缩小转换

Segment::Segment(int new_speed_limit 
, int new_end, double new_length, double new_deceleration) 
:the_speed_limit{ new_speed_limit } 
, the_end{ new_end } 
, the_length{ new_length } 
, deceleration{ new_deceleration } 


{} 

Segment::Segment(double new_end, double new_acceleration) 
    :the_end{ new_end } 
    , acceleration{ new_acceleration } 

{} error here 
double Segment::to_real() const { 
return static_cast<double>((the_end)*(the_end)/(2 * (the_length))); 
while (acceleration) 
{ 
    (acceleration >= 0); 
     return static_cast<double> ((the_end) /(1 * (acceleration))); 
} 
} 

请别人帮助的感谢
我得到的错误是:错误C2397:从“双”到“廉政”的转换需要一个收缩转换

+0

指示哪条线路导致错误。 –

+2

您需要包含一个正确的[mcve],在这种情况下,包括与此类关联的.h文件。从上下文中不清楚发生错误的位置。 – Xirema

+0

@NeilButterworth谢谢我 – yoyooyoyo

回答

0

The error由你一个double的转换引起int在第二个Segment构造函数中。从您的代码的上下文中,我会假设the_end被定义为int,但您将其指定为double

Segment::Segment(double new_end, double new_acceleration) 
    : the_end{ new_end },    // <-- Here 
    acceleration{ new_acceleration } 
{ 

} 

您使用特别的初始化列表中导致错误,因为他们do not allow for narrowing

特别值得注意的是您的具体情况:

  • 一个浮点值不能转换为整数类型。

要修正这个错误,只是提供了一个明确的转换:

Segment::Segment(double new_end, double new_acceleration) 
    : the_end{ static_cast<int>(new_end) }, 
    acceleration{ new_acceleration } 
{ 

} 

待办事项当然从int强制转换为double(整数截断,数据可能丢失从去的潜在危险8字节到4字节等)。