c++中指针类中的[]方括号是什么意思?

What does a [] square bracket mean in pointer class in C++?

本文关键字:方括号 是什么 意思 指针 c++      更新时间:2023-10-16
class Box
{
public:
    // Constructor definition
    Box(double l = 2.0, double b = 2.0, double h = 2.0)
    {
        cout << "Constructor called." << endl;
        length = l;
        breadth = b;
        height = h;
    }
    double Volume()
    {
        return length * breadth * height;
    }
private:
    double length;     // Length of a box
    double breadth;    // Breadth of a box
    double height;     // Height of a box
};
int main(void)
{
    Box Box1(3.3, 1.2, 1.5);    // Declare box1
    Box Box2(8.5, 6.0, 2.0);    // Declare box2
    Box *ptrBox;                // Declare pointer to a class.
                                // Save the address of first object
    ptrBox = &Box1;
    ptrBox[0]; // <--- What does it do?
}
ptrBox[0]

等价于:

*ptrBox

指针支持与数组相同的索引操作符。除了关联的存储之外,数组变量只是指向数组第一个元素的指针,因此可以用语义相同的方式对指针和数组进行索引。