progC.pdf progC-s.pdf progC-e.pdf 記事一覧 |
実行結果 |
p32.cpp は強引な配列の初期化 (真似しない方がいい?)
/* --- p31.cpp (半角 < を全角 < で置換)--- */
#include <stdio.h>
#include <string.h>
//void tshow(char*, tnode*); //tnode() の前だからエラー
/*--------------------------------------
typedef struct tnode{
int d; struct tnode *l, *r;
void show(char *s, tnode *p){
//::tshow(s, p); //エラー
}
} tnode;
--------------------------------------*/
struct tnode{
public:
int d; struct tnode *l, *r;
void show(char *s, tnode *p);
};
void tshow(char *s, tnode *p){
char sl[8], sr[8];
if(p == NULL) return;
strcpy(sl, s); strcpy(sr, s);
tshow(strcat(sl, "L"), p->l);
printf("%s: %d\n", s, p->d);
tshow(strcat(sr, "R"), p->r);
}
void tnode::show(char *s, tnode *p){
::tshow(s, p); //tshow() の後だからOK
}
//--------------------------------------
int main(void){
tnode tn[16]={
{5}, {3, (tn+4), tn}, {9},
{7, (tn+1), (tn+2)}, {2}
};
tn[0].show("", tn+3);
return 0;
}
/* --- p32.cpp (半角 < を全角 < で置換)--- */
#include <stdio.h>
#include <string.h>
class Node{public:
int d; Node *l, *r;
Node(void){d = 0; l = r = NULL;}
void show(char *s, Node *p){
char sl[8], sr[8];
if(p == NULL) return;
strcpy(sl, s); strcpy(sr, s);
show(strcat(sl, "L"), p->l);
printf("%s: %d\n", s, p->d);
show(strcat(sr, "R"), p->r);
}
};
typedef struct tnode{int d; Node *l, *r;} tnode;
int main(void){
Node n[8];
tnode tn[8]={
{5}, {3, (n+4), n}, {9}, {7, (n+1), (n+2)}, {2}
};
Node *p=n;
for(int k = 0; k < 8; k++){
//n[k].d = tn[k].d; n[k].l = tn[k].l; n[k].r = tn[k].r;
*p = *((Node *)(int)(tn+k)); p++; //一応OK
//正統派は reinterpret_cast を使うそうです[3](2014-02-03)
}
n[0].show("", n+3);
return 0;
}
参考資料([n]は本文でも引用, *.pptはブロック解除が面倒なので未調査):
[1] C++。クラス内に、引数付きコンストラクタを持つクラスの配列を生成する
http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q14115618084
[2] その13 引数付きコンストラクを持つクラスの配列を初期化する方法
http://marupeke296.com/TIPS_No13_ClassArrayInitialize.html
[3] C++編(言語解説) 第24章 C++独自のキャスト
http://www.geocities.jp/ky_webid/cpp/language/024.html
CSample* p = reinterpret_cast<CSample*>( num ); //int num;
※コメント投稿者のブログIDはブログ作成者のみに通知されます