int* test_prt(const vector<int>* array, const int index)
{
return array+index;
}
爲什麼第一個參數不能是const?在這種情況下,「const」意味着什麼不能被修改?const vector <T> *哪部分是const?
int* test_prt(const vector<int>* array, const int index)
{
return array+index;
}
爲什麼第一個參數不能是const?在這種情況下,「const」意味着什麼不能被修改?const vector <T> *哪部分是const?
將const
放在類型名稱後面很常見,因爲它啓用了「const to the left rule」。
這是一樣的,你寫的東西:
int* test_prt(vector<int> const* array, const int index)
{
return array+index;
}
這裏,左側的項目是載體,所以這是一個指向常向量。
如果你不使用這個約定,唯一的特例是當const
完全在左邊(const的左邊沒有什麼東西),這意味着它適用於右邊的東西const
。
我也會刪除前面的整數「const」。 因爲它是按值傳遞的阿根廷,
int* test_prt(vector<int> const* array, int index)
{
return array+index;
}
array + index
不修改任何array
或index
,它只是計算兩個操作數的總和,而不會影響原有的,所以代碼工作作爲它應該。這裏的const
表示矢量和index
不能以任何方式改變。例如,如果我試圖改變array
小號的元素之一,我得到一個錯誤:
array[0] = 5; // error! assignment of read-only value
這同樣適用於index
。順便說一句,我認爲你的函數簽名應該已被寫入:
int* test_prt(const vector<int>& array, const int index)
{
return &array[index];
// or &array.at(index) which performs bounds checking
}
也就是說,我們把向量作爲參考,並使用其內部緩衝區的從第一個元素偏移指出。採取引用是非常重要的,因爲它避免了副本,並且返回指向本地副本的指針將是未定義行爲。你的原始代碼只有在array
是一個實際的向量數組時纔會起作用!
而僅僅是明確的,這裏是你如何調用該函數:
std::vector<int> v = {1, 2, 3, 4, 5};
std::cout << test_ptr(v, 1); // prints the address of the 2nd element
您確定要傳遞'的std :: VECTOR'作爲指針? –
不會編譯:'array + index'與'array'的類型相同,不能轉換爲返回類型'int *'。 – aschepler