sam*_*joe 2 c++ stack pointers new-operator
请参考此处给出的代码:
此代码是C++中堆栈实现的一部分:
代码1:
void Stack::pop()
{
if (top != 0) {
node* temp = top;
top = top -> link;
delete temp;
}
}
Run Code Online (Sandbox Code Playgroud)
代码2:
void Stack::pop()
{
if (top != 0) {
node* temp = new node;
temp = top;
top = top -> link;
delete temp;
}
}
Run Code Online (Sandbox Code Playgroud)
在第一个例子中,我没有使用new,而我确实在第二个中使用了它.在运行时,两者都给出完整程序的相同输出,可以在下面找到:
#include <iostream>
using namespace std;
struct node {
string name;
node* link;
};
class Stack
{
node* top;
public:
Stack();
void push(string s);
void pop();
void display();
~Stack(){}
};
Stack::Stack() {
top = 0;
}
void Stack::push(string s)
{
node* temp = new node;
temp -> name = s;
temp -> link = top;
top = temp;
}
void Stack::pop() // Function in question
{
if (top != 0) {
node* temp = new node;
temp = top;
top = top -> link;
delete temp;
}
}
void Stack::display()
{
node* temp = new node;
temp = top;
while (temp != 0)
{
cout << temp -> name << "\n";
temp = temp -> link;
}
}
int main() {
Stack s;
s.push("Ra");
s.push("Sa");
s.push("Ga");
s.pop();
s.display();
}
Run Code Online (Sandbox Code Playgroud)
在这里使用和不使用新指针有什么区别?
内存也会自动释放,或者我必须在析构函数中执行此操作吗?如果是这样,怎么办?
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |