私はC ++を初めて使用します。スタックを実装しようとしています。デフォルトのコンストラクターarr
内で名前付き変数を宣言しています。
しかし、コードをコンパイルすると、次のようなエラーが発生します
'arr' was not declared in this scope
私のコード:
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
class Stack
{
private:
int top = -1;
int n = 100;
public:
Stack()
{
int arr[n]; // 100 element stack
}
void push(int element)//push element to the top of the stack
{
if (isFull() == false)
{
// push element
top += 1; //increment top
arr[top] = element;
}
else cout << "\nStack is full! Can't push element\n";
}
void pop()
{
if (isEmpty() == false)
{
top -= 1;//decrement top
}
}
bool isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool isFull()
{
if (top == n - 1)
return true;
else
return false;
}
int peek(int position)// item at specific location
{
if (position > top)
{
cout << "\nInvalid position\n";
return -1;
}
else
{
return arr[position];
}
}
int count()// number of items
{
return top + 1;
}
void change(int position, int value) // change item at specific location
{
if (position > top)
{
cout << "\nInvalid postion\n";
}
else
{
arr[position] = value;
}
}
void display() // display elements stored
{
if (isEmpty() == false)
{
cout << endl;
for (int i = 0; i < top; i++)
{
cout << arr[i] << endl;
}
}
else
{
cout << endl << "Stack is empty! No elements to display" << endl;
}
}
};
int main()
{
Stack st;
cout << endl;
cout << st.isEmpty();
st.push(10);
cout << endl;
cout << st.isEmpty();
st.display();
return 0;
}
私のエラー:
stack.cpp: In member function 'void Stack::push(int)':
stack.cpp:28:4: error: 'arr' was not declared in this scope
28 | arr[top] = element;
| ^~~
stack.cpp: In member function 'int Stack::peek(int)':
stack.cpp:68:11: error: 'arr' was not declared in this scope
68 | return arr[position];
| ^~~
stack.cpp: In member function 'void Stack::change(int, int)':
stack.cpp:85:4: error: 'arr' was not declared in this scope
85 | arr[position] = value;
| ^~~
stack.cpp: In member function 'void Stack::display()':
stack.cpp:96:11: error: 'arr' was not declared in this scope
96 | cout<<arr[i]<<endl;
| ^~~
なぜこれが起こっているのか分かりません。
arr
すべてのメンバー関数にアクセスできるべきではありませんか?
ザ・
int arr[n]; // 100 element stack
コンストラクタ(スコープ)内にのみ存在するローカル変数です。他のメンバーはこの配列について知らないので、それがエラーの理由です。
配列宣言をプライベートセクションに移動し、n
コンパイル時に認識される必要があります
class Stack
{
private:
int top = -1;
static constexpr int n = 100; // n as static constexpr
int arr[n]{ 0 }; // move `arr` here and optionally initlize to `0`
public:
Stack() = default;
// ... rest of the code
};
補足として、配列操作を行うとき(つまり、push
メンバーの場合と同様)、渡されたに対して境界チェックを行いposition
ます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加