2014-02-25 38 views
1

我已經在我的.h和.cpp文件中有一個構造函數,它需要一些參數,但我也需要一個默認參數,我不知道如何做,因爲我嘗試編譯的方式,但是當我運行我的時候出現錯誤testfile的。 這是我的.h文件C++默認構造函數有問題嗎?

public: 
Class(); 
Class(const std::string &, const int) 
void getInfo(); 
std::string listItem(); 

private: 

std::string name; 
int quantity; 

這是我的.cpp文件

Class::Class() 
: name(0), quantity(0) 
{ 
Class::Class(const string &nam, const int quant) 
: name(nam),quantity(quant) 
{ 
} 
void Class::getInfo() 
{ 
cout << "Enter Name: "; 
cin >> name 
cout << "Enter quantity: "; 
cin >> quantity; 
} 
string Class::listItem() 
{ 
ostringstream outputString; 
outputString << getName() << getQuantity(); 
return outputString.str(); 
} 

這是我測試的部分造成麻煩:

const int shortList = 2; 
array<Class*, shortList> newList; 

for (int i=0; i< 2; i++){ 
     Class *p = new Class(); 
     p->getInfo(); 
     newList[i] = p; 
} 
cout << "newList contains: " << endl; 
for (Class* p : newList) 
      cout << p->listItem() << endl; 

我得到:終止叫在拋出'std :: logic_error'的實例之後 what():basic_string :: _ S_construct null無效

它是一個構造函數問題還是它的一些語法錯誤?

回答

3

的問題是在默認構造函數的初始化器列表:

name(0) 

這試圖初始化使用構造採取C風格的字符串指針,char const*,空指針值的字符串。然後,您將得到一個運行時錯誤,因爲您不允許將空指針傳遞給該構造函數。

初始化字符串是空的,要麼指定默認初始化(或迂腐,值初始化,這相當於同樣的事情,對於這種類型的)

name() 

或離開它的初始化器列表。

+0

非常感謝! – user3348712

0

假設在上面的代碼中沒有故意輸入錯誤,在非常關鍵的位置有一些分號丟失,以及在標題中看起來不正確和缺少聲明的大括號使用。

class Class  // added 
{     // added 
public: 
    Class(); 
    Class(const std::string &, const int); // added semi-colon 
    void getInfo(); 
    std::string listItem(); 

private: 
    std::string name; 
    int quantity; 
}; // added closing curly brace and semi-colon 

在.cpp源文件:

Class::Class() 
: name(""), quantity(0) // modified name initial value to the empty string 
{ 
} // added curly brace 

Class::Class(const string &nam, const int quant) 
: name(nam),quantity(quant) 
{ 
} 

void Class::getInfo() 
{ 
    cout << "Enter Name: "; 
    cin >> name; // added semi-colon 
    cout << "Enter quantity: "; 
    cin >> quantity; 
} 
string Class::listItem() 
{ 
    ostringstream outputString; 
    outputString << getName() << getQuantity(); 
    return outputString.str(); 
} 

後來

新線和/或字符與評論開始// added ...

與頭文件開始注意到在代碼是造成適合是:

const int shortList = 2; 
array<Class*, shortList> newList; 

for (int i=0; i< shortList; i++){ // changed bounds check for i to the const int shortList 
    Class *p = new Class(); 
    p->getInfo(); 
    newList[i] = p; 
} 
cout << "newList contains: " << endl; 

// 
// changed to declare auto instead. 
// As a pointer declaration, there is a chance the Class copy constructor is being called 
// inside the loop body prior to the dereference. It should not be, but... 
// In my opinion, it is much more likely that setting the name to a zero initial value 
// in the Class() constructor is the real problem cause as Mike says above. 
// 
for (auto p : newList) 
    cout << p->listItem() << endl;