这个C ++语法是什么意思,为什么它工作? [英] What does this C++ syntax mean and why does it work?

查看:215
本文介绍了这个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]<< '\\\
'
<< y:< p [1]<< '\\\
'
<< z:<< p [2];
}

输出:

  x:2.8 
y:4.2
z:9.5


$ b b

这里发生了什么?为什么这种语法工作? Point类不包含重载的 operator [] ,这里的代码试图自动转换为float。



感谢

div

被隐式转换为 const float * const ,它指向 x 。所以 * p x *(p + 1) y ,等等。
当然,这是一个很奇怪的想法(和令人困惑的!)这样做。通常最好在数组中存储x,y和z,并且有一个函数来获取整个数组,如果他们真的想这样做。


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

解决方案

p is being converted implicitly into a const float* const, which points to x. So *p is x, *(p+1) is y, 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.

这篇关于这个C ++语法是什么意思,为什么它工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆