在 .h 文件中使用 类

Using classes in .h files

好的,有点上下文,我正在创建一个系统,它可以在文件中添加和删除项目。 我首先创建了一个 itemHandler class 来处理我拥有的 Item class 的所有实例。这很好用。 然后我创建了一个表单来输入值,该表单将用于输入值以创建新项目,class 被称为 addItemForm。 所有 classes 都有各自的 .h 和 .cpp 文件(例如 item/itemHandler/addItemForm.h&.cpp)。

我首先在 itemHandler class 中编写了这个名为 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 class 中使用 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 轻量级将减少编译时间并降低进一步依赖问题的风险,因为你的代码库增加了。

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