2017-08-10 57 views
-2

如何初始化convert.gram?無論何時我在類中刪除「克」時,程序都會適當地響應。我試圖把克在構造函數,但它不工作。我是否也正確地構建了一切?謝謝您的幫助!變量需要一個初始化器C++?

代碼:

#include <stdio.h> 
#include <string.h> 
#include <iostream> 
#include <stdlib.h> 
#include <windows.h> 
#include "math.h" 

using namespace std; 

struct grams{ 
    grams(); 
    float converter(float pounds); 

    float gram; 
    float pounds; 
    float answer; 
    }; 

    float grams::converter(float pounds){ 
    answer = pounds * gram; 
    return answer; 
    } 

    grams::grams(){ 
    float convert.gram = 453.592; 
    } 

int main(){ 
    float PtC; 
    grams convert; 

    cout<<"Pound to Gram Converter \n"; 
    cout<<"How Many Pounds Do You Want to Convert? \n"; 

    cin>>PtC; 

    float converter = convert.converter(PtC); 

    cout<<"Answer = "<<converter<<endl; 

return 0; 
} 

錯誤:

C:/Users/lisa/Desktop/codelight c++/time_of_for_loop/for_loop_time/for_loop_time/main.cpp:31:13: error: expected initializer before '.' token 
+4

'float convert.gram = 453.592;'你想在這裏發生什麼? – vu1p3n0x

+0

@ vu1p3n0x該程序將磅轉換爲克。我會擴展這個程序,所以我想用類來組織它。我在那條線上遇到了麻煩。每當轉換克的新實例時,該行將在構造函數中將「gram」設置爲453.592。 –

回答

1

你需要做的僅僅是設置gram什麼; convertgrams的一個實例,所以它的字段將被正確設置。

grams::grams(){ 
    gram = 453.592; 
} 

但初始化類成員更傳統的和高性能的方法是使用一個成員初始化列表,像這樣:

grams::grams() : gram(453.592) { 

} 

此外,一些建議:由於您使用gram爲不變,將它設置爲常數而不是成員會更有意義。你可以將其設置爲靜態成員(和更好的命名)

struct grams { 
    static const float GRAMS_PER_POUND = 453.592; 
    ... 

您還沒有使用成員pound可言;你應該考慮刪除它。因爲在converter函數完成後沒有通過convert使用它,所以存儲answer也沒什麼意義。