使用.h文件中的类

Using classes in .h files

本文关键字:文件 使用      更新时间:2023-10-16

好吧,关于上下文,我正在创建一个系统,它可以添加和删除文件中的项目。我首先创建了一个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文件中真正包含每个标头。