让我首先说我是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