gpt4 book ai didi

c++ - 在默认构造函数中声明 arr 时未在此范围内声明“arr”

转载 作者:行者123 更新时间:2023-12-01 14:37:08 25 4
gpt4 key购买 nike

我是 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 
是仅存在于构造函数(作用域)内的局部变量。其他成员不会知道这个数组,这就是错误的原因。
将数组声明移动到私有(private)部分和 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 进行绑定(bind)检查。 .

关于c++ - 在默认构造函数中声明 arr 时未在此范围内声明“arr”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63258494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com