2017-08-08 58 views
0

我有這段不斷重複的代碼。在我的for循環中,如何將索引更改爲字符串?

g_materialAmbientIndex[0] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[0].ambient"); 
g_materialDiffuseIndex[0] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[0].diffuse"); 
g_materialSpecularIndex[0] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[0].specular"); 

g_materialAmbientIndex[1] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[1].ambient"); 
g_materialDiffuseIndex[1] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[1].diffuse"); 
g_materialSpecularIndex[1] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[1].specular"); 

g_materialAmbientIndex[2] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[2].ambient"); 
g_materialDiffuseIndex[2] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[2].diffuse"); 
g_materialSpecularIndex[2] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[2].specular"); 

我想把它放到一個for循環,但我有問題的字符串參數。下面是我的功能。我不斷收到一個錯誤,指出:

從沒有合適的轉換FUNC 「的std :: basic_string的.....」 到 「常量GLchar *」 存在

for (int i = 0; i < MAX_MATERIALS; i++) 
{ 
    stringstream ss; 
    ss << i; 
    string str = ss.str(); 

    g_materialAmbientIndex[i] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[" + str + "].ambient"); 
    g_materialDiffuseIndex[i] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[" + str + "].diffuse"); 
    g_materialSpecularIndex[i] = glGetUniformLocation(g_shaderProgramID, "uMaterialProperties[" + str + "].specular"); 
} 

回答

0

錯誤消息

從沒有合適的轉換FUNC 「的std :: basic_string的.....」 到 「常量GLchar *」 的存在

手段,即的"uMaterialProperties[" + str + "].ambient"結果類型爲std::string,但glGetUniformLocation預計const GLchar *類型對輸入票面並沒有從std::stringconst GLchar *的自動轉換。

您可以使用std::string::data獲得一個指向std::string的內容,其中有類型const char *和可轉換爲const GLchar *

glGetUniformLocation(g_shaderProgramID, 
    ("uMaterialProperties[" + str + "].ambient").data()); 

您的代碼應以某種方式是這樣的:

for (int i = 0; i < MAX_MATERIALS; i++) 
{ 
    std::string str = "uMaterialProperties[" + std::to_string(i); 

    g_materialAmbientIndex[i] = glGetUniformLocation(g_shaderProgramID, 
     (str + "].ambient").data()); 
    g_materialDiffuseIndex[i] = glGetUniformLocation(g_shaderProgramID, 
     (str + "].diffuse").data()); 
    g_materialSpecularIndex[i] = glGetUniformLocation(g_shaderProgramID, 
     (str + "].specular").data()); 
} 
1

錯誤消息告訴你的一切,你需要知道:

no suitable conversion func from "std::basic_string....." to "const GLchar*" exists

因此該方法不知道如何處理與std::string - 預計一GLchar*。您應該嘗試的第一件事是通過str.c_str()定期char*

1

要將int eger轉換爲字符串表示形式,請使用std::to_string函數。

然後做這樣的事情:

auto str = "uMaterialProperties[" + std::to_str(i) + "].ambient"; 
g_materialAmbientIndex[i] = glGetUniformLocation(g_shaderProgramID, str.c_str());