c++kquote>中括號在 c++ 中有以下含義:數組元素索引指針對象解引用容器元素迭代下標運算符重載特殊情況下函數調用(當函數名重載了運算符時)
中括號在 C++ 中的含義
中括號([])在 C++ 中具有以下含義:
1. 數組索引
中括號用于訪問或修改數組元素。例如:
<code class="c++">int numbers[5]; numbers[0] = 10;</code>
登錄后復制
2. 指針解引用
中括號可以用于解引用指針,訪問指針指向的對象。例如:
<code class="c++">int* ptr = new int(10); *ptr = 20;</code>
登錄后復制
3. 容器迭代
中括號可用于迭代容器中元素,例如向量、隊列和鏈表。例如:
<code class="c++">vector<int> v = {1, 2, 3}; for (int& i : v) { cout </int></code>
登錄后復制
4. 下標運算符重載
中括號可以被重載,為用戶自定義類型提供下標運算符行為。例如:
<code class="c++">class MyClass { public: int operator[](int index) { return index * 10; } }; MyClass obj; cout </code>
登錄后復制
5. 函數調用(僅限特定情況)
在某些情況下,中括號可用于調用函數,特別是當函數名重載了運算符時。例如:
<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>
登錄后復制
值得注意的是,中括號在不同上下文中具有不同的含義,具體取決于語法和上下文的用途。