gpt4 book ai didi

c++ - 在 .h 文件中使用类

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:08 25 4
gpt4 key购买 nike

好吧,有点上下文,我正在创建一个系统,它可以在文件中添加和删除项目。我首先创建了一个 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 有关,但我已经尝试解决这个问题,但我不明白这个问题。

感谢任何帮助或见解,谢谢。

最佳答案

您不能让 itemHandler.h 依赖于 addItemForm.h 反之亦然。

幸运的是,您不需要!

addItemForm.h 中的代码不需要完整的 itemHandler 定义,只需要知道它是一种类型。那是因为您对它所做的只是声明对它的引用。

所以使用前向声明而不是包含整个 header :

 class itemHandler;

事实上,如果你能以相反的方式做同样的事情,那就更好了——保持你的头文件轻量级将减少编译时间,并降低随着你的代码库增加而进一步出现依赖问题的风险。

理想情况下,您只需要真正将每个 header 包含在 .cpp 文件中即可。

关于c++ - 在 .h 文件中使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34600001/

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