我正在製作一個類似於Minecraft的遊戲,其中所有各種塊都由.h文件中的單個static const Block <name>;
表示。我將它們作爲const Block Block::<name> = Block("name", 0, 0);
在.cpp文件中初始化,並在構造函數中傳遞它使用的紋理的索引(表示爲無符號字符)。在構造函數中,它設置了索引變量,但是當我稍後在程序中嘗試調用它時,它會返回完全不同的值。靜態const對象不是保留值
這裏是重要的部分:
Block::Block(std::string name, uint16 id, uint8 tex)
{
//Check for repeat ids
if (IdInUse(id))
{
fprintf(stderr, "Block id %u is already in use!", (uint32)id);
throw std::runtime_error("You cannot reuse block ids!");
}
_id = id;
idMap.insert(std::make_pair(id, *this));
//Check for repeat names
if (NameInUse(name))
{
fprintf(stderr, "Block name %s is already in use!", name);
throw std::runtime_error("You cannot reuse block names!");
}
_name = name;
nameMap.insert(std::make_pair(name, *this));
_tex = tex;
fprintf(stdout, "Using texture %u\n", _tex);
_transparent = false;
}
uint8 Block::GetIndex() const
{
fprintf(stdout, "Returning texture %u\n", _tex);
return _tex;
}
我傳遞0到構造函數中tex
,並打印作業打印後_tex
出0,所以我知道它是越來越在構造函數中正確設置。但是,稍後當程序調用GetIndex()
時,由於某種原因它總是返回204。我不知道它爲什麼這樣做,但我認爲這可能與我宣佈所有塊爲static const
的事實有關。另外,我知道_tex的值沒有被更改,因爲對象是const
,並且Block在初始化後沒有以任何方式操作。
如果有人知道什麼可能導致此,任何幫助非常感謝。
編輯:
在Block.h,這是聲明塊中的線,內class Block
摘自:
public:
static const Block Test;
然後在Block.cpp,這是朝向頂部的線該文件的:
const Block Block::Test = Block("Test", 1, 0);
使用顯示您的靜態對象的實際申報的模式。還有初始化器的定義。 – AnT
@AndreyT我編輯的帖子包括你在找什麼。 – sm81095
你有沒有在你的課堂上有用戶定義的複製構造函數? – AnT