看板 C_and_CPP 關於我們 聯絡資訊
As title 剛剛寫程式的時候發現的一個問題 void p0(const int){} void p1(const int*){} void p2(const int**){} int main() { int ptr0; int *ptr1; int **ptr2; p0(ptr0); p1(ptr1); p2(ptr2); return 0; } error: invalid conversion from int** to const int** 為什麼無法轉換啊 看起來明明是個很合理的轉換 或是有什麼情況會導致這個轉換出問題嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.175.53 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1423292061.A.AD3.html
lf5471: g++ a.cpp -fpermissive 可以從 error 降成 warning 02/07 15:48
Feis: #1ItZvO1L (C_and_CPP) 02/07 16:35
OPIV: 換成這樣就合法了int *const *p2 02/07 16:49
OPIV: c-faq.com/ansi/constmismatch.html 02/07 16:49
akasan: #1B_2w2Uj 02/07 17:10
johnjohnlin: 所以意思就是 p2 有 const,但是他可能是藉由沒有 02/07 17:55
johnjohnlin: const 的轉上來的,導致了可以亂改他 deref 的結果 02/07 17:56
OPIV: 是啊 只是你是把它pass到另一個函數裡,應該是不會被亂改到 02/07 18:00
OPIV: 還是有什麼方法可以改 我不知道的? 02/07 18:01
Feis: 只要有全域或另外傳入就可能爆炸。 02/08 12:11
RealJack: 函示宣告成void p2(int const*const*)比較適合情境喔 02/08 16:34
OPIV: 那為什麼 const int 和 const int * 就可以? 02/08 20:07
OPIV: 這樣另外傳或有全域也一樣暴啊! 02/08 20:08
avhacker: 每隔一段時間就要重推一次這篇 http://goo.gl/1GDy0 02/08 23:10
TobyH4cker: 看完樓上分享的文之後,倏然跪下了 02/09 22:09