使用.h文件中的类
Using classes in .h files
好吧,关于上下文,我正在创建一个系统,它可以添加和删除文件中的项目。我首先创建了一个itemHandler
类来处理我拥有的Item
类的所有实例。这很好。然后,我创建了一个表单来输入值,该表单将用于输入创建新项目的值,该类被称为addItemForm
。所有类都有各自的.h和.cpp文件(例如item/itemHandler/addItemForm.h
&.cpp
)。
我首先在itemHandler
类中编写了这个名为update
的函数。
void itemHandler::update(int x, int y, SDL_Event e, addItemForm &tmpForm)
{
if( tmpForm.isViewable == false)
{
if(exportButton.mouseAction(x, y, e))
{
//This funtion is pretty self-explanatory. It exports the item's quantity, name and unit to the inventory file in the format: ITEMNAME[ITEMQUANTITY]ITEMUNIT;
exportItemsToFile();
}
if(reloadButton.mouseAction(x, y, e))
{
//This reloads the item to the vector list 'itemList'. This is done in order to delete items as the list must be refreshed.
reloadItems();
}
for(int i = 0; i < itemNumber; i++)
{
//This FOR loop runs the update function for each item. This checks if any action is being preformed on the item, e.g. changing the item quantity, deleting the item etc
itemList.at(i).update( x, y, e );
}
//The 'checking' for if the user wants to delete an item is done within the function 'deleteItem()'. This is why there is not IF or CASE statement checking if the user has requested so.
deleteItem();
}
}
这个功能运行得很好。没有错误,没有警告,什么都没有。
现在跳到我想做同样事情的时候。我希望能够在addItemForm
类中使用itemHandler
函数。所以我写了这个(在addItemForm.h
中):
various includes (SDL, iostream, etc)
include "itemHandler.h"
/...........
...represents everything else/
void updateText(int x, int y, SDL_Event e, itemHandler &tmpHander);
现在,当我写这个,更具体地说,写#include "itemHandler.h"
时,编译器MVSC++2010不喜欢它。它突然说:error C2061: syntax error : identifier 'addItemForm'
,不编译。然而,当我注释掉itemHandler.h的include时,它的工作方式与正常情况类似。*我将头文件包括在所有需要使用它们的地方*
为什么会发生这种情况,唯一的想法是混乱地使用#include
,但我已经尝试过解决这个问题,但我不理解这个问题。
感谢任何帮助或见解,谢谢
不能让itemHandler.h
依赖于addItemForm.h
,反之亦然。
幸运的是,你不需要!
addItemForm.h
中的代码不需要完整的itemHandler
定义,只需要知道它是一种类型。这是因为你所做的只是声明对它的引用
因此,使用正向声明,而不是包括整个标头:
class itemHandler;
事实上,如果你能反过来做同样的事情,那就更好了—保持头部的轻量级将减少编译时间,并随着代码库的增加而降低进一步依赖性问题的风险。
理想情况下,您只需要在.cpp
文件中真正包含每个标头。
- 通过多个头文件使用常量变量
- 生成文件不对文件使用隐式规则
- 两个文件使用彼此的功能-如何解决
- 生成一个生成文件,该生成文件使用Automake在一个步骤中编译和链接所有源文件
- 对同一文件使用 .read 的次数是否有限制?
- 是否有正确的方法对生成文件中的对象文件使用模板命令?(C++)
- 如何在C++中为整个文本文件使用字符串流while循环逻辑
- 如何对继承的文件使用前向声明
- 获取对源文件中特定函数的所有调用并生成其他文件(使用 C、C++预处理器或脚本)
- 从文件(使用strtok()和strcpy())解开数据时进行分割故障
- 在 c++ 中对两个文件使用标头
- 当删除部分依赖列表时,GNU make 对每个对象文件使用相同的源文件
- 如何在文本文件中仅读取一行,该文本文件使用QT具有特定单词
- 我应该只对原始 cpp 文件使用 add_executable() 还是通过 add_library() 创建一个库
- 在 c++ 和 c# 中,对文件容器中包含的文件使用文件路径
- CMD窗口停止工作,文本文件使用fstream读取错误
- 如何在 C++_ 中通过不同目录中的文件使用该变量
- JPEG编码位图(BMP)图像从文件使用libjpeg / C++
- 创建 时出错.SO文件使用Cygwin
- 文件I/O使用C++同时打开两个文件