简体   繁体   English

c ++类返回指向要用作数组的成员的指针

[英]c++ class returning pointer to member to be used as array

class vector3
{
private:
    float x;
    float y;
    float z;
public:
    vector3( float x, float y, float z ) : x(x), y(y), z(z) {}
    // returning pointer to first member to use it as array.
    // assumes that data layout is sizeof(float) by sizeof(float) by sizeof(float)
    // and their order is not changed.
    float* ptr() { return &x; }
    // implicit casting version of ptr()
    operator float*() { return ptr(); }

};

...

vector3 v(1,2,3);
float x = v[0];
float y = v[1];
float z = v[2];

Will it be valid on any platform and any compiler setting? 在任何平台和任何编译器设置上都有效吗? I found this working under visual studio 2013 correctly, but I'm having a feeling that this is quite horribly wrong. 我发现它在Visual Studio 2013下可以正常工作,但是我感觉这是非常错误的。

As a general rule you should prohibit yourself from returning pointer/non-const references of your private data members. 通常,您应该禁止自己返回私有数据成员的指针/非常量引用。

Essential purpose of encapsulation is that state of object ( ie data members ) can only be changed through member functions defined for that class.By returning pointers to data member you are creating another path for changing state which is definitely not a good idea. 封装的基本目的是只能通过为该类定义的成员函数来更改对象(即数据成员)的状态。通过返回指向数据成员的指针,您正在创建用于更改状态的另一条路径,这绝对不是一个好主意。

If efficiency is the main concern then you can return const references. 如果效率是主要问题,则可以返回const引用。

Your feeling is correct. 你的感觉是正确的。

But what's the point? 但是有什么意义呢? Why you don't you just have an array member rather than 3 individual float members? 为什么不只有一个数组成员而不是3个单独的float成员呢?

class vector3
{
private:
    std::array<float, 3> data;
public:
    vector3( float x, float y, float z ) : data( {x, y, z } ) {}
    float* ptr() { return data.data(); }
    operator float*() { return ptr(); }
};

This uses C++11, but you can achieve the same thing with C++03: 它使用C ++ 11,但是您可以使用C ++ 03来实现相同的目的:

class vector3
{
private:
    float data[3];
public:
    vector3( float x, float y, float z )
    {
        data[0] = x;
        data[1] = y;
        data[2] = z;
    }
    float* ptr() { return data; }
    operator float*() { return ptr(); }
};

And of course, the biggest question is: Why don't you just use std::vector or std::array directly? 当然,最大的问题是:为什么不直接使用std::vectorstd::array Your class seems to reinvent the wheel. 您的班级似乎在重新发明轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM