讓我首先說我是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;
}
任何想法,我將如何做構造函數?
[構造函數可以重載](http://en.wikipedia.org/wiki/Function_overloading#Constructor_overloading),就像C++中的任何其他函數一樣。 – chrisaycock 2013-03-20 03:45:15
這是一種很好的做法,即將訪問器成員函數(不會改變對象的函數)聲明爲const,例如'string getcolor()const;'。如果你不這樣做,那麼你的函數就不能被由你的類組成的類的成員函數使用,並且它* do *聲明瞭const。 [點擊這裏查看我在ideone中做過的一個例子](http://ideone.com/1sZwk9)。 – JBentley 2013-03-20 04:56:37