2014-01-23 99 views
0

新的c + +和不能找出爲什麼Visual Studio不喜歡我的「HealthProfile person.setFirstName(第一)」代碼行。錯誤是與「人」,錯誤是沒有默認的構造函數。這可能很痛苦,但我的代碼與我書中的代碼幾乎完全相同。提前致謝!C++需要幫助使用自定義構造函數

主:

#include <iostream> 
#include "HealthProfile.h" 
using namespace std; 

int main() 
{ 
    string first; 
    HealthProfile person; 

    cout << "Enter first name" << endl; 
    getline(cin,first); 
    person.setFirstName(first); 

} 

頭:

#include <string> 
using namespace std; 

class HealthProfile 
{ 
public: 
    HealthProfile(string, string, string, int, int, int, int, int); 
    void setFirstName(string); 
    string getFirstName(); 
    void setLastName(string); 
    string getLastName(); 
}; 

功能:

#include <iostream> 
#include "HealthProfile.h" 

using namespace std; 

HealthProfile::HealthProfile(string first, string last, string g, 
    int m, int d, int y, int h, int w) 
{ 
    setFirstName(first); 
    setLastName(last); 
    setGender(g); 
    setMonth(m); 
    setDay(d); 
    setYear(y); 
    setHeight(h); 
    setWeight(w); 
} 

void HealthProfile::setFirstName(string first) 
{ 
    firstName = first; 
} 
string HealthProfile::getFirstName() 
{ 
    return firstName; 
} 
void HealthProfile::setLastName(string last) 
{ 
    lastName = last; 
} 
string HealthProfile::getLastName() 
{ 
    return lastName; 
} 
+0

編譯器給你什麼錯誤? – 0x499602D2

+3

將'HealthProfile(){}'添加爲公共成員函數。有你的默認構造函數。 – Matt

回答

3

這條線主要:

HealthProfile person; 

聲明使用默認的構造函數HealthProfile類的一個實例。你還沒有聲明一個默認的構造函數。創建您自己的自定義構造函數可以防止爲您隱式創建默認構造函數。如果你想使用默認構造函數以及自定義構造函數,你需要明確聲明並定義它。如果您不想使用默認構造函數,那麼傳入參數以使用您的自定義構造函數。

要在您的.h聲明一個默認的構造函數:

HealthProfile(); 

而在你的.cpp來定義它:

HealthProfile::HealthProfile() { } 

或者只需撥打您現有的自定義構造函數主要:

HealthProfile person(first,last,g,m,d,y,h,w); // AFTER collecting values for these arguments 
+0

感謝您澄清如何使用自定義構造函數,現在有道理。 – TinMan

6

沒有什麼不妥setFirstName()。 的問題是,你聲明一個構造函數,需要三stringsints,由此,能夠消除你正在使用,當你調用HealthProfile person

的解決方法是使用HealthProfile cosntructor並通過了三份strings默認構造函數和五個ints,或聲明並定義一個構造函數,該函數通過將HealthProfile(){}添加到頭中而不帶任何參數。