Last active
August 29, 2015 14:04
-
-
Save chomado/04e76da6246d62905491 to your computer and use it in GitHub Desktop.
変換関数と演算子関数(写経p384)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef ___Class_Counter | |
#define ___Class_Counter | |
#include <climits> | |
class Counter { // カウンタクラス | |
unsigned cnt; // カウンタ | |
public: | |
// 引数を渡すことなく呼び出せるデフォルトコンストラクタ | |
// カウンタを0にするためにデータメンバcntを0で初期化している | |
Counter() : cnt(0) { } | |
/* 変換関数 conversion function | |
operator Type | |
任意の型の値を生成して返却する。*/ | |
// unsigned型への変換関数 | |
operator unsigned() const { return cnt; } | |
/* 演算子関数 operator function | |
☆演算子 の定義: | |
operator☆ | |
これを定義すると、クラス型オブジェクトに☆演算子を適用できるようになる。*/ | |
// 論理否定演算子!。カウンタが0であるかどうかを判定 | |
bool operator!() const { return cnt == 0; } | |
// 前置増分演算子++ | |
Counter& operator++() { | |
if (cnt < UINT_MAX) cnt++; // カウンタの上限はUINT_MAX | |
return *this; // 自分自身への参照を返却 | |
} | |
Counter operator++(int) { | |
Counter x = *this; // デクリメント前の値の保存 | |
++(*this); // 前置増分演算子によってインクリメント | |
return x; // インクリメント前の値を返却 | |
} | |
Counter& operator--() { | |
if (cnt > 0) cnt--; | |
return *this; | |
} | |
Counter operator--(int) { | |
Counter x = *this; | |
--(*this); | |
return x; | |
} | |
}; | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "Counter.h" | |
using namespace std; | |
int main() | |
{ | |
int no; | |
Counter x; | |
Counter y; | |
cout << "カウントアップ回数" << endl; | |
cin >> no; // 4 | |
for (int i=0; i<no; i++) { | |
cout << x++ << ' ' << ++y << endl; | |
} | |
cout << "カウントダウン回数" << endl; | |
cin >> no; // 2 | |
for (int i=0; i<no; i++) { | |
cout << x-- << ' ' << --y << endl; | |
} | |
if (!x) | |
cout << "xは0です" << endl; | |
else | |
cout << "xは0ではありません" << endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
カウントアップ回数 | |
0 1 | |
1 2 | |
2 3 | |
3 4 | |
カウントダウン回数 | |
4 3 | |
3 2 | |
xは0ではありません |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment