開発環境
- OS X Mavericks - Apple, ときどき
Windows 8.1 + Cygwin64, MinGW (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C++ (プログラミング言語)
- g++(コンパイラ)
C++実践プログラミング (スティーブ オウアルライン (著)、Steve Oualline (原著)、Steve Oualline(原著)、望月 康司(翻訳)、クイープ(翻訳) 、オライリー・ジャパン)のⅣ部(高度なプログラミング概念)の24章(テンプレート)、24.10(プログラミング実習)、実習 24-2.を解いてみる。
その他参考書籍
- C++プログラミング入門 (グレゴリー サティア (著)、ダウグ ブラウン (著)、Gregory Satir (原著)、Doug Brown (原著)、望月 康司 (翻訳)、谷口 功 (翻訳)、オライリージャパン)
実習 24-2.
コード(BBEdit, Emacs)
array.cpp
#include <iostream>
#include <string>
class index_error {
public:
const std::string what;
index_error(const std::string& i_what): what (i_what) {}
};
const int SIZE = 100;
template<typename kind>
class array {
private:
kind data[SIZE];
public:
kind& operator [] (const unsigned int index);
};
template<typename kind>
kind& array<kind>::operator [] (const unsigned int index)
{
if (index >= SIZE)
throw index_error("array class index out of range");
return data[index];
}
int main(int argc, char *argv[])
{
array<int> nums;
int i;
for (i = 0; i < 100; ++i)
nums[i] = i * i;
std::cout << nums[10] << std::endl;
try {
std::cout << nums[100] << std::endl;
}
catch (index_error& err) {
std::cerr << "Error: " << err.what << std::endl;
exit (8);
}
catch(...) {
std::cerr << "Error: Unexpected exception occured" << std::endl;
exit (8);
}
return (0);
}
Makefile
CC=g++
CFLAGS=-g -Wall
SRC=test_array.cpp
OBJ=test_array.o
all: test_array
test_array: $(OBJ)
${CC} ${CFLAGS} -o test_array $(OBJ)
test_array.o: test_array.cpp
${CC} $(CFLAGS) -c test_array.cpp
clean:
rm test_array test_array.o
入出力結果(Terminal)
$ make g++ -g -Wall -c test_array.cpp g++ -g -Wall -o test_array test_array.o $ ./test_array 100 Error: array class index out of range $ echo $? 8 $
0 コメント:
コメントを投稿