2017-02-27 80 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字節等)。