2016-03-04 70 views
0

當我編譯這個時,我得到了我的名字函數在Name.cpp中的錯誤標題之前我從來沒有見過這個錯誤。已經有一個在Name.cpp三大功能前一個構造函數,因爲這是錯誤似乎什麼是談論。錯誤:預期的構造函數,析構函數或類型轉換之前的'('令牌

的main.cpp

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

int main() 
{ 

} 

Name.h

#ifndef NAME_H 
#define NAME_H 
#include <iostream> 
#include <string> 
using namespace std; 

class Name 
{ 
    public: 
     Name(); 
     string getFirst(string newFirst); 

     string getMiddle(string newMiddle); 
     string getLast(string newLast); 
     void setFirst(); 
     void setLast(); 
     void setMiddle(); 

    private: 
    string First; 
    string Middle; 
    string Last; 
}; 

#endif // NAME_H 

Name.cpp

#include "Name.h" 
    #include <iostream> 
    #include <string> 
    using namespace std; 
    Name::Name() 
    { 

    } 

    Name::setFirst(newFirst){ 

     Name = newFirst; 
     cout << "You entered: " << Name << endl; 

    } 

    Name::setMiddle(newMiddle){ 

     Middle = newMiddle; 
     cout << "You entered: " << Middle << endl; 

    } 

    Name::setLast(newLast){ 

     Last = newLast; 
     cout<< "You entered: " << Last << endl; 

    } 
+4

題外話:除了你所面臨的問題,那你可能需要一些常見問題解決得1.避免'在標題中使用名稱空間標準,這很容易造成命名空間污染。 (所以在頭文件中,改用'std :: string')。 2.考慮把你的輸入參數改爲'const std :: string&'3.設置你的輸入參數。3.考慮把你的「getters」改爲'const string&getBlablabla()const' –

+0

請你再解釋一下爲什麼我應該避免命名空間標準? –

+1

不避免名稱空間標準,你應該避免(尤其是在頭文件中)使用名稱空間(或其他'使用'指令)。在谷歌中搜索「C++ using namespace pollution」會給你提供很多信息 –

回答

3

您不能省略參數的類型名稱。寫一個。聲明和定義中的函數原型也必須匹配。

Name.h應該

#ifndef NAME_H 
#define NAME_H 
#include <iostream> 
#include <string> 
using namespace std; 

class Name 
{ 
    public: 
     Name(); 
     string getFirst(); 

     string getMiddle(); 
     string getLast(); 
     void setFirst(string newFirst); 
     void setLast(string newLast); 
     void setMiddle(string newMiddle); 

    private: 
    string First; 
    string Middle; 
    string Last; 
}; 

#endif // NAME_H 

Name.cpp

#include "Name.h" 
#include <iostream> 
#include <string> 
using namespace std; 
Name::Name() 
{ 

} 

void Name::setFirst(string newFirst){ 

    Name = newFirst; 
    cout << "You entered: " << Name << endl; 

} 

void Name::setMiddle(string newMiddle){ 

    Middle = newMiddle; 
    cout << "You entered: " << Middle << endl; 

} 

void Name::setLast(string newLast){ 

    Last = newLast; 
    cout<< "You entered: " << Last << endl; 

} 
相關問題