2010-08-11 46 views
2

我已經被C#編碼過去幾年寵壞了,現在我回到了C++並發現我遇到了一些應該很簡單的東西的麻煩。我爲gamedev使用了一個名爲DarkGDK的第三方庫(任何以db爲前綴的命令),但是DGDK不是問題。試圖使用靜態方法/成員

繼承人我的代碼:

system.h中

#pragma once 

#include <string> 
#include <map> 
#include "DarkGDK.h" 

using namespace std; 

class System 
{ 
public: 
    System(); 
    ~System(); 
    void Initialize(); 

    static void LoadImage(string fileName, string id); 
    static int GetImage(string id); 

private: 
    map<string, int> m_images; 
}; 

System.cpp

#include "System.h" 

System::System() 
{ 
} 

System::~System() 
{ 
} 

void System::Initialize() 
{ 
    dbSetDisplayMode (1024, 640, 32); 
    dbSetWindowTitle ("the Laboratory"); 
    dbSetWindowPosition(100, 10); 

    dbSyncOn  (); 
    dbSyncRate  (60); 

    dbRandomize(dbTimer()); 
} 

void System::LoadImage(string fileName, string id) 
{ 
    int i = 1; 

    while (dbImageExist(i)) 
    { 
     i++; 
    } 

    dbLoadImage(const_cast<char*>(fileName.c_str()), i, 1); 
    m_images[id] = i; 
} 

int System::GetImage(string id) 
{ 
    return m_images[id]; 
} 

這裏的想法是有一個地圖,地圖串對整數值,來訪問圖像用字符串代替硬編碼值。這個課程沒有完成,所以它不處理像卸載圖像。我想在不傳遞System實例的情況下訪問圖像方法,所以我使用了靜態方法。

現在我得到這個錯誤:

blahblah\system.cpp(39) : error C2677: binary '[' : no global operator found which takes type 'std::string' (or there is no acceptable conversion)

如果我改變地圖靜態,我得到這個連接錯誤:

1>System.obj : error LNK2001: unresolved external symbol "private: static class std::map,class std::allocator >,int,struct std::less,class std::allocator > >,class std::allocator,class std::allocator > const ,int> > > System::m_images" ([email protected]@@[email protected][email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@[email protected][email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@@[email protected][email protected][email protected][email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@[email protected]@@@[email protected]@[email protected]@A)

任你明亮的傢伙能幫助我嗎?

+1

很多人亦不贊成使用使用命名空間std的'鏈接;'在頭文件。它可能會污染包含它的任何模塊的命名空間。此外,聲明GetImage和LoadImage爲靜態的原因是什麼?你似乎在使用它們,好像它們不是。 – rlduffy 2010-08-11 06:36:35

+0

關於命名空間的好處,謝謝。我希望這兩個圖像相關的方法是靜態的,這樣我就不必將System的實例傳遞給其他可能想要訪問圖像的類。 – Draknir 2010-08-11 16:53:10

回答

6

第一個是編譯器錯誤,因爲您無法從靜態方法訪問非靜態數據成員。 this指針不會隱式傳遞給靜態方法,因此它們不能訪問綁定到實例的數據成員。

在秒情況下,請注意static map<string,int> m_images;只是一個聲明的一個變量。你需要在源文件中使用map<string, int> System::m_images;定義靜態成員變量。這將擺脫鏈接器錯誤。

+0

感謝您的回答Naveen,我確實意識到地圖應該是靜態的(不知道爲什麼我在我的問題中包含該錯誤)。鏈接器錯誤是什麼讓我,定義它在CPP固定它。乾杯! – Draknir 2010-08-11 16:57:26

1

由於m_images是該類的非靜態成員,因此當您從靜態成員函數訪問該對象時,需要指定要使用其成員的對象m_images。如果只有該類的所有對象共享一個對象m_images,則還需要使其成爲static