这个 C++ 是什么意思?语法的含义以及为什么它有效?
我在查看 OpenDE 的源代码时发现了类上数组索引运算符“[]”的一些奇怪的语法用法。下面是一个显示语法的简化示例:
#include <iostream>
class Point
{
public:
Point() : x(2.8), y(4.2), z(9.5) {}
operator const float *() const
{
return &x;
}
private:
float x, y, z;
};
int main()
{
Point p;
std::cout << "x: " << p[0] << '\n'
<< "y: " << p[1] << '\n'
<< "z: " << p[2];
}
输出:
x: 2.8
y: 4.2
z: 9.5
这里发生了什么?为什么这个语法有效? Point 类不包含重载的运算符[]
,这里的代码尝试自动转换为浮动到某处。
我以前从未见过这种用法——至少可以说,它看起来确实很不寻常且令人惊讶。
谢谢
I was looking through the source of OpenDE and I came across some wierd syntax usage of the array indexing operator '[]' on a class. Here's a simplified example to show the syntax:
#include <iostream>
class Point
{
public:
Point() : x(2.8), y(4.2), z(9.5) {}
operator const float *() const
{
return &x;
}
private:
float x, y, z;
};
int main()
{
Point p;
std::cout << "x: " << p[0] << '\n'
<< "y: " << p[1] << '\n'
<< "z: " << p[2];
}
Output:
x: 2.8
y: 4.2
z: 9.5
What's going on here? Why does this syntax work? The Point class contains no overloaded operator []
and here this code is trying to do an automatic conversion to float somewhere.
I've never seen this kind of usage before -- it definitely looks unusual and surprising to say the least.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
p
被隐式转换为const float* const
,它指向x
。因此,*p
是x
,*(p+1)
是y
,依此类推。当然,这样做是一个非常奇怪的想法(而且令人困惑!)。通常最好将 x、y 和 z 存储在数组中,并使用一个函数来获取整个数组(如果他们确实想以这种方式执行操作)。
p
is being converted implicitly into aconst float* const
, which points tox
. So*p
isx
,*(p+1)
isy
, and so on.It's a pretty weird idea (and confusing!) to do it this way, of course. It's usually preferable to store x, y, and z in an array and have a function to get the entire array if they really want to do things this way.
这里的想法是通过下标或名称来访问 Point 的成员。但是,如果您想这样做,最好重载
operator[]
,如下所示:这样,如果编译器在浮点数之间插入填充,它仍然可以工作 - 任何人都可以能读懂C++的人应该能够毫无问题地理解它。
The idea here is to give access to the members of the Point by either subscript or name. If you want to do that, however, you'd be better off overloading
operator[]
something like this:This way, if the compiler inserts padding between the floats, it will still work -- and anybody who can read C++ should be able to understand it without any problems.
这只是将成员数据视为数组的一种方法。您也可以使用结构来做到这一点。当您想要可读性但又希望能够迭代简单的数据结构时,这非常有用。一个示例用法是这样声明一个矩阵:
您可以方便地按名称引用每个单元格,但您也可以在任何地方传递指向 m11 的指针(C 会将您的结构视为数组,m11 是第一个元素),并迭代所有元素。
This is just a way of treating your member data as an array. You can also do this with structs. This is useful when you want readability, yet want to be able to iterate over simple data structures. An example use would be to declare a matrix this way:
You can conveniently reference each cell by name, yet you can also pass around a pointer to m11 everywhere (and C will see your struct as an array, m11 being the first element), and iterate over all the elements.