c++ - 指向不同 .h 文件的类指针

标签 c++ class

Helo stack 的人,我的工作需要你们的帮助。所以我必须 .h 文件第一个是类(class),第二个是学生,我尝试创建函数调用 getCourses 但不幸的是它不是那么好。我的实现“类(class) ** 类(class)”没有通过编译,我不知道为什么不是。如果你能帮助我理解我的错误并帮助我修复它们,我会评价谢谢。

getCourse - 返回类(class)列表

我的类(class).h文件

#ifndef _CORSE_H
#define _CORSE_H
#include <iostream>
#include "Student.h"

class Course
{
public:
void init(std::string getName, int test1, int test2, int exam);
std::string getName();
int* getGrades();
double getFinalGrade();

private:
std::string _name;
int _exam;
int _test1;
int _test2;
};

#endif

我的学生 .h 文件-

#ifndef _STUDENT_H
#define _STUDENT_H
#include <iostream>
#include "Course.h"

class Student
{
public:
void init(std::string name, Course** courses, int crsCount);
std::string getName();
void setName(std::string name);
double getAvg();
int getCrsCount();
Course** getCourses();

private:
std::string _name;
Course** courses;
int _crsCount;
};


#endif

我的获取类(class)功能 -

Course** student::getCourses()
{
  return(this->courses);
}

“Course** getCourses();”初始化中的问题,这也适用于 init 函数和 Course** getCourses();功能。 错误 C4430:缺少类型说明符 - 假定为 int。注意:C++不支持default-int

最佳答案

你有一个循环依赖 - 每个标题都试图包含另一个,你最终会在另一个之前定义一个类。这会产生错误,因为您必须先声明一个类型,然后才能使用它的名称。

Course不依赖于 Student根本没有,所以只需删除 #include从那个文件。

Student的定义仅使用指向 Course 的指针所以它不需要完整的定义。它只需要知道类存在,所以你可以替换 #include声明:

class Course;

还有几点:

  • 两个 header 都应包含<string>因为他们使用 std::string ;但不是 <iostream>因为他们不使用任何 I/O 流;
  • 以下划线和大写字母开头的名称,例如 _CORSE_H , 保留。您应该删除下划线。
  • 你错误地大写了Student在最后的代码片段中。

关于c++ - 指向不同 .h 文件的类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26736806/

相关文章:

c++ - 纹理 Opengl 地形?

c++ - 打印并存储到类型类的 vector

c++ - 如何为动态数组实现 operator[]?

c++ - 无法让 Ocean Optics OmniDriver 工作

c# - 在 C# 中通过字符串变量初始化一个类?

python - 如何从Python中的不同文件夹导入类

c++ - 如何在对象数组中打印对象的变量

javascript - 如何使用JS自动在新窗口中打开外部链接(有异常(exception)规则)?

c++ - 你能为已经在堆上的数组分配内存吗

c++ - C/C++ 中的文本索引库