好的,有点背景,我正在创建一个系统,该系统可以添加和删除文件中的项目。
我首先创建了一个itemHandler
类来处理我拥有的Item
类的所有实例。这很好。
然后,我创建了一个表单来输入值,该表单将用于输入用于创建新项目的值,该类称为addItemForm
。
所有类都有各自的.h和.cpp文件(例如item/itemHandler/addItemForm.h
和.cpp
)。
我首先在update
类中编写了一个称为itemHandler
的函数。
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();
}
}
此功能完全正常。没有预期的错误,没有警告,没有。
现在跳到我想做同样事情的时候。我希望能够在
itemHandler
类中使用addItemForm
函数。所以我这样写(用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
定义,只需要知道它是一种类型即可。那是因为您正在使用它来声明对它的引用。
因此,请使用前向声明,而不要包括整个 header :
class itemHandler;
实际上,如果您可以用另一种方法做同样的事情,那就更好了–保持头文件的轻量级将减少编译时间,并随着代码库的增加而降低进一步的依赖关系问题的风险。
理想情况下,您只需要在
.cpp
文件中真正包含每个 header 即可。关于c++ - 在.h文件中使用类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34600001/