【发布时间】:2019-11-10 05:48:04
【问题描述】:
我目前正在尝试在 School.hpp 文件中定义一个“学校”类。 School 类的一部分是称为 roster 的 Student 对象的向量。如果我在 School.hpp 中#include "Student.hpp",编译器会抛出“重新定义‘class Student’”错误。如果我不包含 Student.hpp,它会为 std::vector
我不知道它认为我在哪里重新定义了 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