【问题标题】:Overloading bracket operator as member function重载括号运算符作为成员函数
【发布时间】:2017-03-11 13:18:07
【问题描述】:

我正在为 Vector3D 类型的对象创建一个简单的类。以下代码将完美编译并运行。

class Vector3D {
    float x, y, z;
public:
    Vector3D() = default;
    Vector3D(float a, float b, float c) : x(a), y(b), z(c) {};
    float& operator [](int i) {
        return (&x)[i];
    }
    const float& operator [](int i) const {
        return (&x)[i];
    }
}

int main(int argc, char ** argv){
    Vector3D myVec(1,2,3);
    printf("Value of y: %d\n", myVec[1]);
}

但是,当我删除地址运算符 (&) 时,我得到一个错误并且代码将无法工作。为什么 (&) 是必要的?即:

return (x)[i]; // will not compile "expression must have pointer-to-object type"
return (&x)[i]; // all good here

我也很难理解它是如何工作的。函数如何返回第 i 个浮点数,成员变量是否以连续方式存储在内存中(如数组)?

【问题讨论】:

    标签: c++ reference operator-overloading return-type brackets


    【解决方案1】:

    您这样做的方式非常棘手,这是未定义的行为

    结构成员布局不能保证,但大多数时候成员被放置在内存中:

    x---y---z--- (4 bytes each)
    x[0]
        x[1]
            x[2]
    

    这就是您的代码正常工作的原因(请记住,这不是已定义的行为)。

    您的代码无论如何都不会进行边界检查,因此请考虑:

    1. 将其转换为开关。
    2. 将您的成员设为float x[3] 之类的数组。

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 2011-06-05
      • 2017-07-16
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多