1

我有这堂课:

class Texture
{
    public:
        //I need this variable in this format
        float diffuseColor[3];
}

但我想制作一个比处理“diffuseColor [0]”等更简单的界面,例如:

myTexture.color.r = 1.0f; //this is diffuseColor[0]

所以我试图得到一个类,它作为一个外壳来处理diffuseColor值,比如:

class Color
{
    public:
        float *r, *g, *b;
}

在我的纹理类中:

class Texture
{
    public:
        Texture()
        {
            color.r = &diffuseColor[0];
            color.g = &diffuseColor[1];
            color.b = &diffuseColor[2];
        }

        Color color;
    private:
        float diffuseColor[3];
}

但现在的情况是,如果我想使用颜色值,我必须取消引用它们:

(*myTexture.color.r) = 1.0f;

我怎样才能实现这一点而不必每次我想使用它时取消引用它?

4

2 回答 2

7

您可以使用将在成员初始化器列表中初始化的引用:

struct Color {
    Color(float* colors): r(colors[0]), g(colors[1]), b(colors[2]) {}
    float& r;
    float& g;
    float& b;
};
class Texture {
    float diffuseColor[3];
public:
    Color color;
    Texture(): diffuseColor(), color(this->diffuseColor) {}
};

如果您需要复制和/或分配Texture对象,您还需要实现复制构造函数和赋值运算符。另请注意,这种便利具有相对较高的成本:指针和引用方法都会将Texture对象的大小增加 3 个指针。相反,您可能最好使用访问器,例如:

class Texture {
    float diffuseColor[3];
public:
    float& r() { return this->diffuseColor[0]; }
    float& g() { return this->diffuseColor[1]; }
    float& b() { return this->diffuseColor[2]; }
};
于 2013-08-27T23:25:43.323 回答
4

也许你可以使用 C++ 的联合语言特性:

union ColorUnion {
    // first representation (Texture)
    struct TextureColor {
        float diffuseColor[3];
    }

    // second representation (RGB) 
    struct RGBColor {
        float r;
        float g;
        float b;
    }
};
于 2013-08-27T23:25:31.933 回答