簡體   English   中英

從另一個類訪問靜態成員函數

[英]Accessing a static member function from another class

我在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")

來自其他班級。 網上的其他帖子似乎談論使用extern,但我不確定。 我不明白為什么這與從另一個類調用任何其他成員函數有什么不同?

謝謝,詹姆斯

編輯:是的,我已經宣布了

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

在Timestream.cpp文件的頂部。 在標題中,它被定義為

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

我已將RoomDescription的標題包含在我試圖從這些方法調用的類的標題中。

我得到的錯誤就是這個

Import.obj:錯誤LNK2019:未解析的外部符號“public:static void __cdecl Timestream :: setRoomList(class std :: map,class std :: allocator>,class RoomDescription,struct std :: less,class std :: allocator >> ,類std :: allocator,類std :: allocator> const,類RoomDescription >>>)“(?setRoomList @Timestream @@ SAXV?$ map @ V?$ basic_string @ DU?$ char_traits @ D @ std @@ V ?$分配器@ d @ @@ 2 STD @@ VRoomDescription @@ U&$ @少V'$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@@ 2 @V?$分配器@ U&$對@ $$ CBV?$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@ VRoomDescription @@@ STD @@@ 2 @@ std @@@ Z)在函數“public:int __thiscall Import :: getRoomData(void)”中引用(?getRoomData @ Import @@ QAEHXZ)

Timestream.obj:錯誤LNK2001:未解析的外部符號“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&$ @少V'$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@@ 2 @ V'$分配器@ U&$對@ $$ CBV?$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@ VRoomDescription @@@ STD @@@ 2 @@ @性病@一個)

你需要添加:

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

Timestream.cpp ,或者調用你的實現文件。

這將定義靜態成員。 在頭文件中,您只需聲明它。

我猜測未解析的外部符號是roomList ; 這是錯誤消息中包含的重要信息。 並且,大概是roomList是在類定義中聲明的靜態成員。 如果這些假設是正確的,那么錯誤的原因是代碼沒有roomList定義

通常,靜態成員必須在類定義中聲明並在源文件中定義

// foo.h:
class C {
    static int data;
};

// foo.cpp:
int C::data = 42;

這與從另一個類訪問靜態成員無關。 如果您嘗試從聲明它的類中訪問它,則會收到相同的錯誤。

編輯:從新發布的錯誤消息中,有兩個缺少的名稱: setRoomListroomList 請注意, roomListTimestream的成員,必須這樣定義,也就是說,它的定義必須包含Timestream:: 如上所示,它只是一個全局數據對象,而不是Timestream的成員。 setRoomList的問題可能是相同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM