[問題] struct內成員指派順序是否影響結果
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
06/06 20:37, 1F
→
06/06 20:44, , 2F
06/06 20:44, 2F
→
06/06 20:46, , 3F
06/06 20:46, 3F
→
06/06 20:46, , 4F
06/06 20:46, 4F
→
06/06 21:17, , 5F
06/06 21:17, 5F
→
06/06 21:18, , 6F
06/06 21:18, 6F
→
06/06 21:19, , 7F
06/06 21:19, 7F
→
06/06 21:21, , 8F
06/06 21:21, 8F
→
06/06 21:21, , 9F
06/06 21:21, 9F
→
06/07 00:49, , 10F
06/07 00:49, 10F
→
06/07 15:56, , 11F
06/07 15:56, 11F
→
06/07 15:57, , 12F
06/07 15:57, 12F
→
06/07 16:16, , 13F
06/07 16:16, 13F
→
06/07 16:17, , 14F
06/07 16:17, 14F
→
06/07 16:17, , 15F
06/07 16:17, 15F
→
06/07 16:22, , 16F
06/07 16:22, 16F