[問題] struct內成員指派順序是否影響結果

看板C_and_CPP作者 (Parisienne)時間12年前 (2013/06/06 18:23), 編輯推噓0(0016)
留言16則, 3人參與, 最新討論串1/1
typedef struct Ball CBall; struct Ball{ char *color; double radius; double (*volume)(CBall *); }; double CalVolume(CBall *this){ double r = this->radius; return r * r * 3.14; } void initBall(CBall *ball, char *color, double radius){ ball->volume = CalVolume; ball->color = color; ball->radius = radius; } int main(int argc, char *argv[]) { CBall ball; initBall(&ball, "Red", 5.0); printf("Ball實例的半徑為: %.2f, 體積為: %.2f\n", ball.radius, ball.volume(&ball)); system("PAUSE"); return 0; } 上面的範例中有幾個問題想請教,麻煩了,謝謝。 (1) 在main的printf中,若把ball.volume(&ball)改成ball.volume算出之體積為0.00 ? 原先想法是在main中呼叫iniBall時已把ball的volume(會再去呼叫CalVolume), color, radius的值設定好,但因為ball->volume = CalVolume在 ball->radius = radius前先執行,所以在還沒得知radius的情況下算不出volume, 於是把改成ball->volume = CalVolume放到ball->radius = radius之後執行,但結 果還是0.00,想請問是什麼原因? 還是說使用ball.volume時一定要放參數(&ball)? 如果是這樣,為何initBall定義中 之ball->volume = CalVolume不需要寫成ball->volume(&ball) = CalVolume ? (2) 在strcut定義中的 double (*volume)(CBall *)和函式 void initBall(CBall *ball, char *color, double radius)為什麼要接收指標型式 的CBall? 可以接收非指標型式的CBall嗎? 如改成CBall aa,後面定義中的->都改成. (3) 函式double CalVolume(CBall *this)中,這裡的this指標就是一般常聽到的this 指標? 有什麼用途? 試著改成非指標型式,如double CalVolume(CBall aa),然後後面改 成double r = aa.radius,這樣可以正確執行,只是會有warning如下: In function `initBall': [Warning] assignment from incompatible pointer type 這樣會有什麼問題? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.60.73.76

06/06 20:37, , 1F
(1)ball->volume 是一個 function pointer
06/06 20:37, 1F

06/06 20:44, , 2F
(2)傳 pointer 是避免 copy 整個 struct
06/06 20:44, 2F

06/06 20:46, , 3F
如果你傳入原本的型態,你改的是複製出來的 ball,不是
06/06 20:46, 3F

06/06 20:46, , 4F
main 裡面的 ball
06/06 20:46, 4F

06/06 21:17, , 5F
(3)我猜的你的問題是沒有改 struct Ball 裡的 volume 型態
06/06 21:17, 5F

06/06 21:18, , 6F
double (*)(CBall*) 和 double (*)(CBall) 是不同 pointer
06/06 21:18, 6F

06/06 21:19, , 7F
type. 建議原 PO 把書讀一讀,基本觀念搞懂就知道在幹麻了
06/06 21:19, 7F

06/06 21:21, , 8F
這裡傳 pointer 也是為了避免 copy,的確類似模仿 OOP 裡
06/06 21:21, 8F

06/06 21:21, , 9F
的 this
06/06 21:21, 9F

06/07 00:49, , 10F
都是基本觀念而已... 你一定跳過
06/07 00:49, 10F

06/07 15:56, , 11F
謝謝前輩的回答 是有想到傳pointer可能是避免像傳值
06/07 15:56, 11F

06/07 15:57, , 12F
一樣複製所有的值。 另外(1)的部分還是有些不太懂
06/07 15:57, 12F

06/07 16:16, , 13F
ball->volume = CalVolume 是說,以後 ball->valume() 會
06/07 16:16, 13F

06/07 16:17, , 14F
呼叫到 CalVolume 這個 function,計算是在 call func 時
06/07 16:17, 14F

06/07 16:17, , 15F
我想你應該至少要知道 function pointer 是什麼東西XD
06/07 16:17, 15F

06/07 16:22, , 16F
大概知道我的盲點了...XD 謝謝
06/07 16:22, 16F
文章代碼(AID): #1Hi6C8t9 (C_and_CPP)