2015-04-05 56 views
1

我對C++很新穎,不知道爲什麼我得到這個錯誤,除了我認爲它是爲getter方法使用字符串類型。錯誤在編譯時沒有在類中聲明的成員函數

錯誤消息:

C:\Users\Robin Douglas\Desktop\week6>g++ -c Student.cpp 
Student.cpp:15:31: error: no 'std::string Student::get_name()' member function d 
eclared in class 'Student' 
Student.cpp:20:43: error: no 'std::string Student::get_degree_programme()' membe 
r function declared in class 'Student' 
Student.cpp:25:32: error: no 'std::string Student::get_level()' member function 
declared in class 'Student' 

Student.hpp

#include <string> 

class Student 
{ 
    public: 
     Student(std::string, std::string, std::string); 
     std::string get_name; 
     std::string get_degree_programme; 
     std::string get_level; 
    private: 
     std::string name; 
     std::string degree_programme; 
     std::string level; 
}; 

Student.cpp

#include <string> 
#include "Student.hpp" 

Student::Student(std::string n, std::string d, std::string l) 
{ 
    name = n; 
    degree_programme = d; 
    level = l; 
} 

std::string Student::get_name() 
{ 
    return name; 
} 

std::string Student::get_degree_programme() 
{ 
    return degree_programme; 
} 

std::string Student::get_level() 
{ 
    return level; 
} 

回答

2

下面的代碼定義字段(變量),而隨後的方法。

public: 
    Student(std::string, std::string, std::string); 
    std::string get_name; 
    std::string get_degree_programme; 
    std::string get_level; 

然後,當你實現它的.cpp文件編譯器會抱怨你試圖實現未聲明的方法(因爲你宣佈GET_NAME是一個變量)。

std::string Student::get_name() 
{ 
    return name; 
} 

要解決,只是改變你的代碼如下:

public: 
    Student(std::string, std::string, std::string); 
    std::string get_name(); 
    std::string get_degree_programme(); 
    std::string get_level(); 
+0

謝謝,這個工作:) – 2015-04-05 21:09:39

相關問題