看板 EE_DSnP 關於我們 聯絡資訊
※ 引述《bonoshi (sbo)》之銘言: : Topic5的講義上,第38張slide上的第二點說 : 2. How about: : int *p = new int; : void f(const int* q); : 問:Is f(p) OK? : 答案當然是ok,只要在函式內不要對*q進行修改就行了,可供驗證的程式碼如下 : #include<iostream> : using namespace std; : void f(int const*q); : int main(void){ : int*p=new int; : f(p); : system("pause"); : } : void f(int const*q){ : } : 不過我卻發現一件奇怪的事,如果p是一個double pointer,同樣的語法用下去 : ,就不行了(請看下面) : #include<iostream> : using namespace std; : void f(int const**q); : int main(void){ : int**p=new int*; : *p = new int; : f(p); : system("pause"); : } : void f(int const**q){ : } : compiling error : 按照道理應該要可以執行才對? : 那麼為什麼不可以呢? : 麻煩高手幫忙回答一下 : 謝謝! 就像上課時說的, function call 就是對參數做一個 assignment 的動作. 所以第一個例子: int const* p = int *; // 示意, 當然這樣文法是錯的. 是 OK 的, 因為就是 LHS 收到 copy 下來之後, 就把它當作是 read-only 而已. 但是第二個例子: int const** p = int **; 是不行的, 因為 LHS 是 pointer to a (int const *), 但是 RHS 是 pointer to a (int*). 不同型態的 pointer 是不能互相 assign 的 (void * on the LHS 例外) FYI, 但是如果 f() 改成: void f(int *const *p) { } 就可以了! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 76.126.186.119
bonoshi:其實問這個的緣起,是因為這次作業我將一個double pointer 11/10 21:19
bonoshi:傳入函式,假設那個double pointer是a,因為**a直接指到了 11/10 21:19
bonoshi:矩陣裡面的「元」,因此,我希望**a在傳入函式時,被限定 11/10 21:20
bonoshi:**a不能被修改,才試出了這樣的問題… 11/10 21:21
bonoshi:對了,我想向老師確定一下(int const *)意思是不是 11/10 21:28
bonoshi:(改一下)我想確定一下老師上面說(int const *)意思是不 11/10 21:29
bonoshi:是pointer to int const 11/10 21:29
ric2k1:yes. 11/10 22:43
wintercobra:不懂,最後改成void f(int *const *p){},那個const 11/10 23:42
wintercobra:為什麼加在那個位置?如果要p指向一個(int const *), 11/10 23:43
wintercobra:為什麼不是void f(int const* *p){}? 11/10 23:43
bonoshi:int *const *p的意思是 11/10 23:47
bonoshi:p is a pointer to a constant pointer to an integer 11/10 23:47
bonoshi:下一篇我分享我八點多時做的兩個測試,雖然有點偏了… 11/10 23:49
ric2k1:To wintercobra, please see post 1571 bonoshi's test 11/11 02:15