gpt4 book ai didi

C++ 类没有被正确包含

转载 作者:行者123 更新时间:2023-11-30 01:31:47 24 4
gpt4 key购买 nike

我有一个问题,要么我完全无法理解,要么非常奇怪。这可能是第一个,但我整个下午都在谷歌上搜索没有成功,所以这里......

我有一个名为 Schedule 的类,它的成员是 Room vector 。但是,当我使用 cmake 或什至手动编译时,我得到以下信息:

In file included from schedule.cpp:1:
schedule.h:13: error: ‘Room’ was not declared in this scope
schedule.h:13: error: template argument 1 is invalid
schedule.h:13: error: template argument 2 is invalid
schedule.cpp: In constructor ‘Schedule::Schedule(int, int, int)’:
schedule.cpp:12: error: ‘Room’ was not declared in this scope
schedule.cpp:12: error: expected ‘;’ before ‘r’
schedule.cpp:13: error: request for member ‘push_back’ in ‘((Schedule*)this)->Schedule::_sched’, which is of non-class type ‘int’
schedule.cpp:13: error: ‘r’ was not declared in this scope

以下是相关的代码:

#include <vector>

#include "room.h"

class Schedule
{
private:
std::vector<Room> _sched; //line 13
int _ndays;
int _nrooms;
int _ntslots;
public:
Schedule();
~Schedule();
Schedule(int nrooms, int ndays, int ntslots);
};
Schedule::Schedule(int nrooms, int ndays, int ntslots):_ndays(ndays), _nrooms(nrooms),_ntslots(ntslots)
{
for (int i=0; i<nrooms;i++)
{
Room r(ndays,ntslots);
_sched.push_back(r);
}
}

理论上,g++ 应该先编译一个包含它的类。这里没有循环依赖,都是直截了当的东西。我完全被这个难住了,这让我相信我一定错过了一些东西。 :-D

编辑:
room.h 的内容来自以下评论:

#include <vector>  
#include "day.h"

class Room
{
private:
std::vector<Day> _days;

public:
Room();
Room(int ndays, int length);
~Room();
};

最佳答案

即使您省略了一些重要的代码(即 day.h 的内容),我的心理调试器感觉告诉我您的头文件中存在循环依赖:

// schedule.h
#include "room.h"

// room.h
#include "day.h"

// day.h
#include "schedule.h"

这很糟糕。为了打破循环依赖,你需要弄清楚哪个文件不需要知道其他文件的具体实现细节。这是使用前向引用完成的。例如,我可以看到您对 Room 类的定义实际上不需要知道类定义的 sizeof(Day) 是什么,因此您可以重写它如下:

#include <vector>
// do NOT include day.h

class Day; // forward declaration
class Room
{
private:
std::vector<Day> _days;

public:
Room();
Room(int ndays, int length);
~Room();
};

现在 room.h 不依赖于 day.h,打破了循环依赖。当然,实现文件room.cpp仍然需要包含day.h

关于C++ 类没有被正确包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2715045/

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