2016-03-13 20 views
0

如何創建一個在運行時計算大小的GLTexture nullptrs數組? 。下面的實現創建一個數組GLTexture指針,初始化爲nullptr,常量大小爲[11] [32]。我希望下面頭文件中顯示的11和32與運行時計算的值互換。如何在不構建對象的情況下在運行時設置數組大小?

頭文件

#pragma once 
    #include <GLEW\glew.h> 
    #include "GLTexture.h" 

     namespace Nova 
     { 
      class TextureBinder 
      { 
      private: 
       GLuint  m_activeUnit; 
       GLint  m_maxTextureUnits; 
       GLint  m_maxTextureTargets; 
       GLTexture* m_boundTextures[11][32] = {nullptr}; 

      public: 

       static TextureBinder& GetInstance() 
       { 
        static TextureBinder binder; 
        return binder; 
       } 

       TextureBinder(TextureBinder const&) = delete; 
       void operator=(TextureBinder&) = delete; 


      private: 
       TextureBinder(); 
      }; 
     } 

CPP文件

#pragma once 
#include "TextureBinder.h" 

namespace Nova 
{ 
    /* zero is the default opengl active texture unit 
    - glActiveTexture(unit) only needs to be called for multitexturing 
*/ 
      TextureBinder::TextureBinder() 
     : 
     m_activeUnit(0), 
     m_maxTextureTargets(11) 
    { 
     glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &m_maxTextureUnits); 
    } 
} 
+0

哪個變量是你想要的數組大小?你的代碼很長。 –

+0

@ArifBurhan對不起,錯過了! m_boundTextures [m_maxTextureTargets] [m_maxTextureUnits] – DanielCollier

+0

是指向此類擁有的紋理的m_boundTextures指針,還是在別處管理的? –

回答

1

這簡單的代碼替代方法是使用:

std::vector< std::vector<GLTexture*> > m_boundTextures; 

,並加入到構造函數初始化程序列表

// Numbers can be replaced by variables, 
// or you can set the size later using 'resize' member function 
m_boundTextures(11, std::vector<GLTexture*>(32)); 

另一種選擇是使用尺寸11 * 32的一個載體來考慮(或任何你的尺寸是),然後使用乘法來訪問正確的索引;你可以爲此做一個幫手功能,例如:

GLTexture* & lookup(size_t row, size_t col) { return m_boundTextures.at(col + row * row_length); } 
+0

如果我像m_boundTextures.resize(11)那樣調用m_boundTextures的resize成員函數;我將如何更改其內的std :: vector 的大小? – DanielCollier

+1

爲一個,'m_boundTextures [n] .resize(32);'。對於所有的一次,'for(auto&x:m_boundTextures)x.resize(32);' –

+0

謝謝!完美的作品 – DanielCollier

2

假設你真的想要一個動態大小的數組(即可以在運行時計算,並與不同尺寸的作品),你需要使用一個循環在你的構造函數中:

GLTexture* **m_boundTextures; 

TextureBinder() { 
    /* ... */ 
    m_boundTextures = new GLTexture* *[HEIGHT]; 
    for(int i = 0; i < HEIGHT; i++) { 
     m_boundTextures[i] = new GLTexture* [WIDTH]; 
     for(int j = 0; j < WIDTH; j++) { 
      m_boundTextures[i][j] = nullptr; 
     } 
    } 
    /* ... */ 
} 

當然,確保清理內存使用刪除[ ](以相同的格式)在你的析構函數中。

+0

或者可能使用'std :: vector',當你調整它的大小時,你可以設置一個默認值;) –

+0

我更喜歡其他答案,但是+1,因爲我學到了一些新東西! – DanielCollier

相關問題