パスワードを忘れた? アカウント作成
585350 journal

bananan_wの日記: 今日のC++実践プログラミング実習 13-3, 22-1 2

日記 by bananan_w
#if 0
C++実践プログラミング 第二版
実習13-3
シンプルなキューを実装する。
データはFIFOで処理される。

実習22-1
キューに例外を実装する
#endif

#include <cstdlib>
#include <iostream>
#include <assert.h>

const int QUEUE_SIZE = 100;

class bound_err {
        public:
                const std::string what;
                bound_err(const std::string& i_what): what(i_what) {}
                // bound_err& operator = -- default
                // bound_err(bound_err) -- default copy constructor
                // bound_err() -- default destructor
};

class queue {
        private:
                int count; // キューに格納されているデータ数
                int index; // 次にgetされるデータのインデックス
                int data[QUEUE_SIZE];
        public:
                queue(){
                        count = 0;
                        index = 0;
                };
                // copy constructor : default
                // operator = : default
                // destructor : default

                void put(const int item) throw(bound_err);

                int get() throw(bound_err);
};

inline void queue::put(const int item) throw(bound_err)
{
        if ((count < 0) ||
                ( count >= static_cast<int>(sizeof(data)/sizeof(data[0])))) {
                throw bound_err("Push overflows queue");
        }
        data[count] = item;
        count++;
}

inline int queue::get() throw(bound_err)
{
        int value;
        count--;

        if ((count < 0) ||
                (count >= static_cast<int>(sizeof(data)/sizeof(data[0])))){
                throw bound_err("Push underflows queue");
        }
        if (index < static_cast<int>(sizeof(data)/sizeof(data[0]))){
                value = data[index];
                index++;
        } else {
                index = 0;
                value = data[index];
        }
        return(value);
}

static queue test_queue;

static void put_a_lot()
{
        int i;

        for(i=0; i < 5000; i++) {
                test_queue.put(i);
        }
}

int main()
{
        try {
                put_a_lot();
        }
        catch (bound_err& err) {
                std::cerr << "Error: Bounds exceeded\n";
                std::cerr << "Reason: " << err.what << '\n';
                exit(8);
        }
        catch (...) {
                std::cerr << "Error: Unexpected exeption occurred\n";
                exit(8);
        }
        return(0);
}
この議論は賞味期限が切れたので、アーカイブ化されています。 新たにコメントを付けることはできません。
typodupeerror

吾輩はリファレンスである。名前はまだ無い -- perlの中の人

読み込み中...