// スタックを初期化する
s1.init();
s2.init();
s1.push('o');
s1.push('l');
s1.push('l');
s1.push('e');
s1.push('H');
s2.push('d');
s2.push('l');
s2.push('r');
s2.push('o');
s2.push('W');
for(i=0; i<5; i++) cout << "s1をポップする: " << s1.pop() << "\n";
for(i=0; i<5; i++) cout << "s2をポップする: " << s2.pop() << "\n";
|
「スタックは一杯です」と表示され、それ以上スタックにデータをプッシュできない。
それを実現しているのは、クラス実現部の push 関数の以下の部分である。
if(tos==SIZE) {
cout << "スタックは一杯です";
return;
}
|
#define SIZE 10 |
char stck[SIZE]; // スタック領域を確保する |
初期化によって tos の値を 0 にするため。 初期化しないと tos の値は不定であり、stck[tos] によって、意図しないメモリ領域に読み書きしてしまうことがある。 |
初期化しないとメモリが確保されない。 |
コンストラクタが自動的に呼び出され、その内部で tos=0 と初期化されるから |
コンストラクタによって自動的に初期化されるから |
#include <iostream>
#include <cmath>
using namespace std;
class complex{
private:
double real; // 実部
double imag; // 虚部
public:
complex(double r,double i); // コンストラクタ
double get_real();
double get_imaginary();
double get_norm();
void show();
};
// コンストラクタ
complex::complex(double r,double i){
real = r;
imag = i;
}
double complex::get_real(){
return real;
}
double complex::get_imaginary(){
return imag;
}
double complex::get_norm(){
return sqrt(real*real+imag*imag);
}
void complex::show(){
cout << real << "+" << imag << "i\n";
}
|
…
class complex{
private:
double a; // 実部
double b; // 虚部
public:
…
douuble get_norm();
};
…
double complex::get_norm(){
a = sqrt(a*a+b*b); //← (※)
return a;
}
|
double complex::get_norm(){
double r = sqrt(a*a+b*b);
return r;
}
|
void complex::get_real(){
cout << "real part is " << real << "\n";
}
|
double complex::get_norm(){
double r=real*real+imag*imag;
sqrt(r); // ←(※)
return r;
}
|