2013-03-20 64 views
0

讓我首先說我是C++的初學者。我正試圖編寫一個程序,簡單地詢問用戶3個輸入。兩個是字符串,一個是整數。我已經爲此編寫了以下課程:關於通過獲取和設置方法傳遞字符串

#include <string> 
#include <sstream> 

using namespace std; 

class Cellphone 
{ 
private : 
     string itsbrand; 
    string itscolor; 
    int itsweight; 

public : 
    string tostring(); 
     void setbrand(string brand); 
     string getbrand() ; 
    void setcolor(string color); 
    string getcolor(); 
    void setweight(int weight); 
    int getweight(); 


}; 

一切工作正如我需要它,除了我需要兩個構造函數。一個沒有參數數據,一個沒有參數數據。我很困惑,甚至從建設者開始,所以如果有人可以提供一點洞察力,我將不勝感激。這裏是我的主要():

int main() 
{ 
    Cellphone Type; 

    int w; 
    string b, c; 

    cout << "Please enter the Cellphone brand : "; 
    getline(cin, b); 
    Type.setbrand (b); 
    cout << "Please enter the color of the Cellphone : "; 
    getline(cin, c); 
    Type.setcolor (c); 
    cout << "Please enter the weight of the Cellphone in pounds : "; 
    cin >> w; 
    Type.setweight (w); 
    cout << endl; 
    cout << Type.tostring(); 
    cout << endl; 
} 

任何想法,我將如何做構造函數?

+2

[構造函數可以重載](http://en.wikipedia.org/wiki/Function_overloading#Constructor_overloading),就像C++中的任何其他函數一樣。 – chrisaycock 2013-03-20 03:45:15

+0

這是一種很好的做法,即將訪問器成員函數(不會改變對象的函數)聲明爲const,例如'string getcolor()const;'。如果你不這樣做,那麼你的函數就不能被由你的類組成的類的成員函數使用,並且它* do *聲明瞭const。 [點擊這裏查看我在ideone中做過的一個例子](http://ideone.com/1sZwk9)。 – JBentley 2013-03-20 04:56:37

回答

2

C++類中的構造函數可以被重載。

  1. 構造沒有給出參數,通常被稱爲「默認構造函數 」。如果你的類沒有定義任何構造函數, 編譯器會爲你生成一個「默認構造函數」。 「默認構造函數」是一個可以在不提供任何參數的情況下調用的構造函數。

  2. 當爲這個類的新對象創建這些參數 時,使用帶給定參數的構造函數。如果 你的類定義了一個帶參數的構造函數,那麼 編譯器不會爲你生成一個「默認構造函數」,所以當你創建一個需要默認構造函數的對象時, 會導致編譯錯誤。因此,您決定是否根據您的應用程序提供默認構造函數和重載構造函數。

例如,在您的CellPhone類中,如果需要,可以提供兩個或多個構造函數。

默認構造方法:您所提供某種默認值的類

public CellPhone(): itsbrand(""), itscolor(""), itsweight(0){ 
     //note that no formal parameters in CellPhone parameter list 
} 

構造函數的成員參數:

public CellPhone(string b, string c, int w): itsbrand(b), itscolor(c), itsweight(w) 
{ 
} 

您還可以定義一個構造函數,所有提供的默認值給定參數,根據定義,這也稱爲「默認構造函數」,因爲它們具有默認值。實施例下面給出:

public CellPhone(string b="", string c="", int w=0): itsbrand(b),itscolor(c),itsweight(w) 
{ 
} 

這些是關於構造用C重載一些方面++;

+0

謝謝你給我解釋了很多。 – Dolbyover 2013-03-20 04:01:00

+0

@ZachKenny當然。不用謝。 – taocp 2013-03-20 04:02:13

相關問題