过去几年我一直被 C# 编码宠坏了,现在我又回到了 C++ 并发现我在处理本应很简单的东西时遇到了麻烦。我正在为 gamedev 使用名为 DarkGDK 的第三方库(任何以 db 为前缀的命令),但是 DGDK 不是问题。
这是我的代码:
系统.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;
};
系统.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" (?m_images@System@@0V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HU?$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@@H@std@@@2@@std@@A)
你们中的任何聪明人都可以帮助我吗?
最佳答案
第一个是编译器错误,因为您无法从静态方法访问非静态数据成员。 this
指针不会隐式传递给静态方法,因此它们无法访问绑定(bind)到实例的数据成员。
在秒的情况下,注意 static map<string,int> m_images;
只是变量的声明。您需要使用 map<string, int> System::m_images;
来定义静态成员变量在源文件中。这将消除链接器错误。
关于c++ - 尝试使用静态方法/成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3455394/