2017-02-15 188 views
0

我需要創建一個程序,它有3個集合,3個以及構造函數。然而,當我創建的默認構造函數,它給了我,指出我們需要有一個「)」前「」排隊默認構造函數C++格式

#include <string> 

class Vehicle 
{ 
public: 
    Vehicle(std::string vehicleType, int numberOfDoors, int maxSpeed) 
     : type{vehicleType}, number{numberOfDoors}, speed{maxSpeed}{} 
    void setType(std::string vehicleType) { 
       type = vehicleType;} 
    void setNumber(int numberOfDoors){ 
        number = numberOfDoors;} 
    void setSpeed(int maxSpeed) { 
       speed = maxSpeed;} 

    Vehicle(string, int, int); 
    ~Vehicle(); 
    Vehicle(); 
    std::string getType() const {return type;} 
    int getNumber() const {return number;} 
    int getSpeed() const {return speed;} 

private: 
    std::string type; 
    int number; 
    int speed; 
}; 

有人能告訴我什麼是錯的錯誤?

+0

'汽車(字符串,INT,INT);' - 它應該是'的std :: string'。 'string'不是這裏的類型的名字。 – yeputons

+0

爲什麼你聲明兩次相同的構造函數? '車輛(std :: string vehicleType,int numberOfDoors,int maxSpeed)'和'Vehicle(string,int,int)'。 – iosdude

+0

@iosdude 如果我把它放在一邊,它會告訴我未識別的車輛參考:車輛,這意味着沒有默認構造函數 – xx123

回答

0

您需要刪除Vehicle(string, int, int);,因爲它已經被定義。 (檢查你的第一個構造函數)

+0

如果我刪除Vehicle(string,int,int); 然後它告訴我我需要一個默認的構造函數。它給了我一個「Vehicle :: Vehicle」的無法識別的引用 – xx123

+0

您可以刪除'Vehicle();'和'〜Vehicle();' 或者像@swapnil建議的那樣 - 'Vehicle()= default;'和'〜 Vehicle()= default;'如果在C++ 11上。 – grubs

1

你已經在你的類的開頭定義了三個參數構造函數,你使用成員初始值設定項列表初始化類Vehicle的成員變量。因此,您不需要再次聲明它:

Vehicle(string, int, int); 

如果您刪除此行,您的代碼將被編譯。見here

當你實例化你的類,你需要提供三個參數,一個string和兩個int小號

此外,如果你想有一個默認的構造,可以將下面一行添加到您的類。

Vehicle():type(), number(0), speed(0){} 

那麼你應該能夠實例化Vehicle類不帶任何參數和用戶setter函數值設置爲這樣一個對象的成員變量。

而且要麼刪除沒有定義析構函數或定義的析構函數,也許是這樣的:

~Vehicle(){ type.clear();} 

here