错误编译时没有在类中声明的成员函数

时间:2015-04-05 19:22:42

标签: c++

我对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;
}

1 个答案:

答案 0 :(得分: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();