在C ++中,[]方括号在指针类中意味着什么?

时间:2016-08-12 12:16:05

标签: c++ pointers

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?

}

1 个答案:

答案 0 :(得分:1)

ptrBox[0]

相当于:

*ptrBox

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