首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不构造对象的情况下在运行时设置数组大小?

如何在不构造对象的情况下在运行时设置数组大小?
EN

Stack Overflow用户
提问于 2016-03-13 20:01:54
回答 2查看 51关注 0票数 0

如何创建一个在运行时计算大小的GLTexture nullptrs数组?下面的实现创建了一个以nullptr初始化的数组GLTexture指针,其大小为11。我希望将下面的头文件中显示的11和32与在运行时计算的值交换。

头文件

代码语言:javascript
复制
#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文件

代码语言:javascript
复制
#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);
    }   
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-13 20:22:35

代码的最简单的替代方法是使用:

代码语言:javascript
复制
std::vector< std::vector<GLTexture*> > m_boundTextures;

并添加到ctor-初始化程序列表中。

代码语言:javascript
复制
// 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的向量(或您的维度),然后使用乘法来访问正确的索引;您可以为此创建一个辅助函数,例如:

代码语言:javascript
复制
GLTexture* & lookup(size_t row, size_t col) { return m_boundTextures.at(col + row * row_length); }
票数 1
EN

Stack Overflow用户

发布于 2016-03-13 20:13:22

假设您实际上想要一个动态大小的数组(即可以在运行时计算并具有不同的大小),那么您需要在构造函数中使用一个循环:

代码语言:javascript
复制
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;
        }
    }
    /* ... */
}

当然,确保在析构函数中使用deletein the same format清除内存。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35975114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档