前提・実現したいこと
int型の数値を上限なく保持することができるようなスタック管理のクラスを作成しようとしています.
具体的には,以下のようなメンバ関数を持つようなクラスです.
- push関数
• スタックに数値を追加し,追加した数値を返す.
失敗時はERROR値を返す.
- pop関数
• スタックから数値を取り出し,数値を返す.
失敗時(スタックが空の場合など)はERROR値を返す
以下のようにかなりエラーが発生してしまいました.
メンバ関数内でmallocやfreeは使用できないのか,それとも他に原因があるのでしょうか...
発生している問題・エラーメッセージ
エラーメッセージ In member function ‘int Stack::push(int)’: 31:46: error: ‘malloc’ was not declared in this scope stack *next=(stack *)malloc(sizeof(stack)); ^ In member function ‘int Stack::pop()’: error: ‘free’ was not declared in this scope free(p); ^ error: ‘retern’ was not declared in this scope retern x; ^ error: expected ‘;’ before ‘x’ retern x;
該当のソースコード
C++ ソースコード //スタック実装 //スタック上限を設けない #include <stdio.h> #define ERROR -9999 typedef struct st{ int count; int num; struct st *pointer; }stack; class Stack { stack *stack_pointer; public: Stack(); ~Stack(); int push(int number); int pop(void); }; Stack::Stack() { stack_pointer->count=0; } Stack::~Stack() { printf("スタックに%d個の数字が入った状態で終了しました\n", stack_pointer->count); } int Stack::push(int number) { stack *next=(stack *)malloc(sizeof(stack)); if(next != NULL){ next->num = number; next->pointer=stack_pointer; stack_pointer=next; stack_pointer->count++; printf("スタックに%dを入れました\n", number); return number; } else{ printf("スタックが満杯です\n"); return ERROR; } } int Stack::pop(void) { if(stack_pointer->count != 0){ int x=stack_pointer->num; stack *p=stack_pointer; stack_pointer=p->pointer; free(p); retern x; } else{ stack_pointer->count--; printf("スタックは空です"); return ERROR; } } // 動作検証(テスト) int main() { Stack s; // 機能確認 printf("%d\n", s.push(10)); printf("%d\n", s.push(20)); printf("%d\n", s.push(30)); printf("%d\n", s.pop()); printf("%d\n", s.pop()); printf("%d\n", s.pop()); // 2個pushした状態で終了) s.push(120); s.push(220); printf("\n"); }
試したこと
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/18 15:03
2018/11/19 01:17