[英]Overloading bracket operator as member function
我正在為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
我也很難理解它的工作原理。 函數如何返回ith浮點數,成員變量是否以連續方式存儲在內存中(如數組)?
您執行此操作的方式非常棘手,這是未定義的行為 。
無法保證結構成員的布局,但是大多數情況下,將成員放置在內存中的方式如下:
x---y---z--- (4 bytes each)
x[0]
x[1]
x[2]
因此,這就是代碼正常運行的原因(請記住,這不是定義的行為)。
您的代碼無論如何都不會進行邊界檢查,因此請考慮:
float x[3]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.