gpt4 book ai didi

c++ - 从另一个类访问静态成员函数

转载 作者:太空狗 更新时间:2023-10-29 20:44:49 24 4
gpt4 key购买 nike

我在 C++ 类中有一个静态 STL 映射,并有另一个静态成员函数返回指向映射中对象的常量指针。该映射对类中的所有对象都是通用的。

唯一的问题是,我需要搜索这个映射并从另一个类中设置它,它位于不同的 .cpp/.h 文件中,当我尝试在 vs2010 中编译它们时,我得到了无法解析的外部符号。这些方法在 Timestream 类中定义为

static void setRoomList(std::map<std::string, RoomDescription> rl);
static RoomDescription * getRoom(std::string ref);

这两个函数都是公开的,所以应该没有访问问题。这些函数在 Timestream.cpp 文件中定义为正常,即,

RoomDescription * Timestream::getRoom(std::string ref)
{
std::map<std::string, RoomDescription>::iterator cIter= roomList.find(ref);

if(cIter!=roomList.end())
return &(cIter->second);

return NULL;
}

我想这样调用它

RoomDescription *r =Timestream::getRoom("Bathroom")

来自其他类(class)。网络上的其他帖子似乎在谈论使用 extern,但我不确定。我不明白为什么这与从不同类调用任何其他成员函数有什么不同?

谢谢,詹姆斯

编辑:是的,我已经声明了

std::map<std::string, RoomDescription> roomList;

在 Timestream.cpp 文件的顶部。在 header 中它被定义为

static  std::map<std::string, RoomDescription> roomList;

我已将 RoomDescription 的 header 包含在我试图从中调用这些方法的类的 header 中。

我得到的错误是这样的

Import.obj : error LNK2019: unresolved external symbol "public: static void __cdecl Timestream::setRoomList(class std::map,class std::allocator >,class RoomDescription,struct std::less,class std::allocator > >,class std::allocator,class std::allocator > const ,class RoomDescription> > >)" (?setRoomList@Timestream@@SAXV?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@VRoomDescription@@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@VRoomDescription@@@std@@@2@@std@@@Z) referenced in function "public: int __thiscall Import::getRoomData(void)" (?getRoomData@Import@@QAEHXZ)

Timestream.obj : error LNK2001: unresolved external symbol "private: static class std::map,class std::allocator >,class RoomDescription,struct std::less,class std::allocator > >,class std::allocator,class std::allocator > const ,class RoomDescription> > > Timestream::roomList" (?roomList@Timestream@@0V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@VRoomDescription@@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@VRoomDescription@@@std@@@2@@std@@A)

最佳答案

你需要添加:

std::map<std::string, RoomDescription> Timestream::roomList;

Timestream.cpp,或者您调用的任何实现文件。

这将定义 静态成员。在头文件中,您只需声明即可。

关于c++ - 从另一个类访问静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12161697/

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