gpt4 book ai didi

c++ - 编译时报错no member function declared in class

转载 作者:行者123 更新时间:2023-11-30 03:54:34 26 4
gpt4 key购买 nike

我是 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'

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

关于c++ - 编译时报错no member function declared in class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com