2013-03-20 45 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

相关问题