【问题标题】:Trying to use an object in another class's header file, getting "redefinition of class" error试图在另一个类的头文件中使用一个对象,得到“类的重新定义”错误
【发布时间】:2019-11-10 05:48:04
【问题描述】:

我目前正在尝试在 School.hpp 文件中定义一个“学校”类。 School 类的一部分是称为 roster 的 Student 对象的向量。如果我在 School.hpp 中#include "Student.hpp",编译器会抛出“重新定义‘class Student’”错误。如果我不包含 Student.hpp,它会为 std::vector 抛出“'Student' is not declared in this scope”错误。

我不知道它认为我在哪里重新定义了 Student 类,因为我只有一次 Student 的类定义,并且在 Student.hpp 文件中。

// School.hpp
#include <vector>
#include "Student.hpp"

class School
{
    // instance variables
    std::vector<Student> roster;

我是 C++ 新手,并且正在完成一些老派项目,如果这是我的一个愚蠢的错误,我深表歉意。

【问题讨论】:

  • 我猜“Student.hpp”被多次收录。尝试在 .hpp 文件的顶部添加 #pragma once
  • 或者,如果您想要 C++ 标准支持的方法,请使用包含防护。 #pragma once 被某些人认为是“事实上的标准”,大多数现代编译器都支持它,但标准 C++ 实际上并不支持。 #pragma once 的拥护者倾向于指出优点(是的,有很多),但假装没有缺点(其中也有几个)。

标签: c++ class compiler-errors header-files redefinition


【解决方案1】:

您似乎没有告诉预处理器必须包含一次头文件。

在每个头文件('*.hpp')的顶部,添加以下行:

#pragma once

欲了解更多信息,请参阅this article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2013-02-17
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多