编辑: 正如DyP在下面的评论中指出的那样,这只是c3(SoccerWorld)中函数定义中的一个拼写错误。
c1
,它有一个虚函数f
。c2
继承自c1
,另一个c3
继承自c2
。c2
没有虚拟函数f
,但我想将其添加到c3
并进行一些更改。f
中的虚拟函数c1
不纯,在c1.cpp
中定义。我仍然需要f
加入c1
。将f
添加到c3
而非c2
时,我收到一个未解决的外部符号错误。如果我将f
添加到c2
作为虚拟函数,我会收到两个错误:一个与以前相同,另一个在c1.obj
中表示f
已存在c3
。
这是c1
,c2
,c3
的样子:
class C1 {
virtual void f() { ... }
};
class C2 : public C1 {
//No virtual f
};
class C3 : public C2 {
virtual void f() { /*Do something*/ }
};
真正的f函数:
AbstractKart *World::createKart(const std::string &kart_ident, int index, int local_player_id, int global_player_id, RaceManager::KartType kart_type)
{ ... }
这是在世界级。类WorldWithRank继承自World,并且没有createKart函数。类SoccerWorld继承自WorldWithRank,我希望它有createKart,这样如果它是一个SoccerWorld,我会放置不同的卡丁车。
createKart在World中受到保护。
错误:
world.obj : error LNK2005: "protected: virtual class AbstractKart * __thiscall World::createKart(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,int,int,int,enum RaceManager::KartType)" (?createKart@World@@MAEPAVAbstractKart@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HHHW4KartType@RaceManager@@@Z) already defined in soccer_world.obj
soccer_world.obj : error LNK2001: unresolved external symbol "protected: virtual class AbstractKart * __thiscall SoccerWorld::createKart(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,int,int,int,enum RaceManager::KartType)" (?createKart@SoccerWorld@@MAEPAVAbstractKart@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HHHW4KartType@RaceManager@@@Z)
答案 0 :(得分:3)
从评论转发给OP:
从你的错误中猜测,我认为你有一个错字。在soccer_world.cpp
中,您定义了一个函数AbstractKart *World::createKart(...)
,而不是AbstractKart *SoccerWorld::createKart(...)
。
这会创建AbstractKart *World::createKart(...)
的第二个定义,它解释了第一个错误:
world.obj:错误LNK2005:“
protected: virtual class AbstractKart * __thiscall World::createKart([...])
”[...] 已在soccer_world.obj中定义
如果您尝试调用未定义的AbstractKart *SoccerWorld::createKart(...)
:
soccer_world.obj:错误LNK2001:未解析的外部符号“
protected: virtual class AbstractKart * __thiscall SoccerWorld::createKart([...])
”[...]
答案 1 :(得分:1)
你总是可以在C2类中定义f():
class C2 : public C1 {
virtual void f() { C1::f(); }
};
这将使C2能够像C3从未存在一样发挥作用。