编译时类中未声明任何成员函数时出错

Error no member function declared in class when compiling

本文关键字:成员 函数 出错 任何 未声明 编译      更新时间:2023-10-16

我对c++还很陌生,不知道为什么会出现这个错误,只是我认为这与使用getter方法的字符串类型有关。

错误消息:

C:UsersRobin DouglasDesktopweek6>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'

学生.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;
};

学生.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;
}

下面的代码定义字段(变量)而不是方法。

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();