C++映射变量地址?

Dan*_*cco 1 c++

我有这门课:

class Texture
{
    public:
        //I need this variable in this format
        float diffuseColor[3];
}
Run Code Online (Sandbox Code Playgroud)

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

myTexture.color.r = 1.0f; //this is diffuseColor[0]
Run Code Online (Sandbox Code Playgroud)

所以我试图得到一个类作为diffuseColor值的shell,类似于:

class Color
{
    public:
        float *r, *g, *b;
}
Run Code Online (Sandbox Code Playgroud)

在我的Texture类中:

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

        Color color;
    private:
        float diffuseColor[3];
}
Run Code Online (Sandbox Code Playgroud)

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

(*myTexture.color.r) = 1.0f;
Run Code Online (Sandbox Code Playgroud)

如何在不想每次使用它的情况下取消引用它的情况下实现这一目标?

Die*_*ühl 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) {}
};
Run Code Online (Sandbox Code Playgroud)

如果需要复制和/或分配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]; }
};
Run Code Online (Sandbox Code Playgroud)