オブジェクト指向プログラミングa 2013年度定期試験対策要点解説 4. typedefによる型の別名定義

●typedefによる型の別名定義に関する教材資料はこちら

■問題1

  下記のmain関数の前に,下図の Integer, kilometer, Country, Ship, ArrayOfInt5 の別名を定義せよ。
その際,ただ書き写すのではなく,下図の手順1~3のように考えながら書くこと。



01#include <stdio.h>
02  
03/* ここに,Integer, kilometer, Country, Ship, ArrayOfInt5 の型名を typedef で定義せよ。 */
04 
05 
06 
07 
08 
09  
10int main() {
11  
12    Integer i = 10;           /* int型の変数i */
13     
14    kilometer fromHome = 1.2; /* 家からの距離を表す変数 */
15  
16    Country myCountry = Japan; /* 国別コードを格納する変数 myCountry */
17  
18    Ship myShip = { 100, 100, 10, 0 }; /* シューティングゲームの自機を表す変数 myShip */
19  
20    ArrayOfInt5 a = { 5, 8, 1, 0, 9 }; /* int型要素5個を持つ配列変数a */
21  
22    printf( "i is %d\n", i );
23    printf( "myCountry is %d\n", myCountry );
24    printf( "myShip : x is %d, y is %d, life is %d, graphic is %d\n", myShip.x, myShip.y, myShip.life, myShip.graphic );
25    for( i = 0; i < 5; i++ ) printf( "a[%d] is %d\n", i, a[i] );
26  
27    getchar(); getchar();
28    return 0;
29}

【解答例】
01#include <stdio.h>
02  
03typedef int Integer;
04  
05typedef double kilometer;
06  
07typedef enum Country {
08  America, Japan, UK, USA = 0
09} Country;
10  
11typedef struct Ship {
12  int x, y, life, graphic;
13} Ship;
14  
15typedef  int ArrayOfInt5[ 5 ];
16  
17int main() {
18  
19    Integer i = 10;           /* int型の変数i */
20     
21    kilometer fromHome = 1.2; /* 家からの距離を表す変数 */
22  
23    Country myCountry = Japan; /* 国別コードを格納する変数 myCountry */
24  
25    Ship myShip = { 100, 100, 10, 0 }; /* シューティングゲームの自機を表す変数 myShip */
26  
27    ArrayOfInt5 a = { 5, 8, 1, 0, 9 }; /* int型要素5個を持つ配列変数a */
28  
29    printf( "i is %d\n", i );
30    printf( "myCountry is %d\n", myCountry );
31    printf( "myShip : x is %d, y is %d, life is %d, graphic is %d\n", myShip.x, myShip.y, myShip.life, myShip.graphic );
32    for( i = 0; i < 5; i++ ) printf( "a[%d] is %d\n", i, a[i] );
33  
34    getchar(); getchar();
35    return 0;
36}