重载括号运算符作为成员函数
Overloading bracket operator as member function
我正在为 Vector3D 类型对象制作一个简单的 class。以下代码将编译并 运行 完美。
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
我什至无法理解它是如何工作的。函数如何可以 return 第 i 个浮点数,成员变量是否以连续的方式存储在内存中(如数组)?
您这样做的方式非常棘手,这是未定义的行为。
不保证结构成员布局,但大多数情况下成员在内存中的放置方式为:
x---y---z--- (4 bytes each)
x[0]
x[1]
x[2]
这就是您的代码正常工作的原因(请记住,这 不是 已定义的行为)。
您的代码无论如何都不会进行边界检查,因此请考虑:
- 正在将其转换为开关。
- 将您的成员放入数组中,例如
float x[3]
。
我正在为 Vector3D 类型对象制作一个简单的 class。以下代码将编译并 运行 完美。
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
我什至无法理解它是如何工作的。函数如何可以 return 第 i 个浮点数,成员变量是否以连续的方式存储在内存中(如数组)?
您这样做的方式非常棘手,这是未定义的行为。
不保证结构成员布局,但大多数情况下成员在内存中的放置方式为:
x---y---z--- (4 bytes each)
x[0]
x[1]
x[2]
这就是您的代码正常工作的原因(请记住,这 不是 已定义的行为)。
您的代码无论如何都不会进行边界检查,因此请考虑:
- 正在将其转换为开关。
- 将您的成员放入数组中,例如
float x[3]
。