Home >Backend Development >C++ >What do square brackets mean in c++
The square brackets have the following meanings in C: array element index pointer object dereference container element iteration subscript operator overloading special case function call (when the function name overloads the operator)
The meaning of square brackets in C
The square brackets ([]) have the following meanings in C:
1. Array index
Brackets are used to access or modify array elements. For example:
<code class="c++">int numbers[5]; numbers[0] = 10;</code>
2. Pointer dereference
Square brackets can be used to dereference a pointer and access the object pointed to by the pointer. For example:
<code class="c++">int* ptr = new int(10); *ptr = 20;</code>
3. Container iteration
Brackets can be used to iterate elements in containers, such as vectors, queues and linked lists. For example:
<code class="c++">vector<int> v = {1, 2, 3}; for (int& i : v) { cout << i << endl; }</code>
4. Subscript operator overloading
The square brackets can be overloaded to provide subscript operator behavior for user-defined types. For example:
<code class="c++">class MyClass { public: int operator[](int index) { return index * 10; } }; MyClass obj; cout << obj[2] << endl; // 输出 20</code>
5. Function call (only in certain cases)
In some cases, square brackets can be used to call functions, especially when the function name is repeated When the operator is loaded. For example:
<code class="c++">class Point { public: int x, y; Point operator+(const Point& other) const { return {x + other.x, y + other.y}; } }; Point p1 = {1, 2}; Point p2 = {3, 4}; Point p3 = p1 + p2; // 使用中括号调用 + 运算符</code>
It’s worth noting that brackets have different meanings in different contexts, depending on the syntax and context’s purpose.
The above is the detailed content of What do square brackets mean in c++. For more information, please follow other related articles on the PHP Chinese website!