これは非常に迅速な回答になると感じています。私は iOS 開発に関する Paul Hegarty のスタンフォード コースを受講していますが、彼はキャスティングについて言及しています。私はJavaの経験がありますが、キャストに遭遇したことはないので、これはキャストに関する一般的な質問かもしれません. オンラインで簡潔な説明を見つけることができないようです。彼が与えるコードは次のとおりです。
@interface Vehicle
- (void)move;
@end
@interface Ship : Vehicle
- (void)shoot;
@end
Ship *s = [[Ship alloc] init];
[s shoot];
[s move];
Vehicle *v = s;
[v shoot];
id obj = ...;
[obj shoot];
[obj someMethodNameThatNoObjectAnywhereRespondsTo];
// I understand up to this far, but it's the casting I'm having difficulty with
NSString *(hello) = @"hello";
[hello shoot];
Ship *helloShip = (Ship *)hello;
[helloShip shoot];
したがって、最初の行で、hello という名前の NSString へのポインターを作成します。2 行目で、彼は NSString である hello の shot メソッドを呼び出しますが、そのメソッドは存在しないため機能しません。3 行目では、helloShip という Ship オブジェクトへのポインタを作成し、それを何に等しく設定していますか? NSString ポインターがシップ ポインターに変換 (キャスト?) されましたか? その場合、なぜシュートの呼び出しが失敗するのですか?