问题描述
error c2504未定义基类,编译错误,和#include头文件有关。
感谢
详细描述
(代码引自Cocos2d-x手游开发Mario)
Item.h
...
#include "ItemMushroom.h"
class Item:public CCSprite
{
...
public:
static Item* create(CCDictionary* dict);
...
}
Item.cpp
#include "Item.h"
...
Item* Item::create(CCDictionary* dict)
{
const CCString* type = dict->valueForKey("type");
if (type->m_sString == "mushroom")
{
return ItemMushroom::create(dict);
}
return NULL;
}
...
因为我在Item.cpp文件 函数static Item* create(CCDictionary* dict); 的实现中用到了ItemMushroom类的成员函数,所以在Item.h文件中 引用了ItemMushroom.h头文件。
然而我的ItemMushroom类是派生自Item
ItemMushroom.h
#include "Item.h"
class ItemMushroom:public Item
{
...
};
那么问题来了,在Item.h头文件中我包含了ItemMushroom.h,
在ItemMushroom.h头文件中又包含了Item.h,在包含的顺序上出现了闭合环状。
原因分析:
编译器首先编译Item.h,因为其包含ItemMushroom.h,引入ItemMushroom.编译,ItemMushroom继承自Item,Item尚未编译成功。此时VS2013 报错error 2504: Item 未定义基类。此错误是在编译Item.h头文件出错。
解决方法
头文件在包含顺序上不要成闭合环状,顺序结构最好应该是树。
Item.h 中删除#include "ItemMushroom.h"
Item.cpp 中加入#include "ItemMushroom.h"
Item.cpp
#include "Item.h"
#include "ItemMushroom.h"
...
Item* Item::create(CCDictionary* dict)
{
const CCString* type = dict->valueForKey("type");
if (type->m_sString == "mushroom")
{
return ItemMushroom::create(dict);
}
return NULL;
}
...
本文分析并解决了C++编程中因头文件包含顺序不当导致的error C2504:未定义基类的问题。通过调整Item.h和ItemMushroom.h之间的依赖关系,避免了闭合环状包含,最终消除了编译错误。
293

被折叠的 条评论
为什么被折叠?



