概要
- 1つのクラスに対して複数のオブジェクトを作ることができる。
- 今回はstackクラスに対して、s1とs2という名前でオブジェクトを作成する。
- オブジェクト同士は干渉しない
study21.cpp
#include <iostream>
using namespace std;
#define SIZE 10
class stack {
char stck[SIZE];
int tos;
public:
void init();
void push( char ch );
char pop();
};
void stack::init() {
tos = 0;
}
void stack::push( char ch ) {
if ( tos == SIZE ) {
cout << "スタックはいっぱいです";
return;
}
stck[tos] = ch;
tos++;
}
char stack::pop() {
if ( tos == 0 ) {
cout << "スタックは空です";
return 0;
}
tos--;
return stck[tos];
}
int main() {
stack s1, s2;
int i;
s1.init();
s2.init();
s1.push('a');
s2.push('x');
s1.push('b');
s2.push('y');
s1.push('c');
s2.push('z');
for ( i=0; i<3; i++ ) cout << "s1をポップする:" << s1.pop() << endl;
for ( i=0; i<3; i++ ) cout << "s2をポップする:" << s2.pop() << endl;
return 0;
}
g++ -o study21 study21.cpp
実行
s1をポップする:c
s1をポップする:b
s1をポップする:a
s2をポップする:z
s2をポップする:y
s2をポップする:x
引用・参考はこちら
独習C++ 第4版
https://www.amazon.co.jp/dp/4798119768