更改队列指针成员的值需要在 C++ 中出现奇怪的错误

change queue pointer member's value will need to weired fault in c++

本文关键字:C++ 错误 队列 指针 成员      更新时间:2023-10-16

我是 c/c++ 的新手,遇到了一个非常奇怪的问题。 下面的这个简单代码将导致分段错误。 谁能告诉我这个问题怎么会发生? 谢谢

#include <queue>
#include <iostream>
using namespace std;
class hhh{
private:
public:
int *root=NULL;
void cons(){
queue<int*> q;
q.push(root);
q.front()=new int(8);
cout<<*(q.front())<<endl;
cout<<*root<<endl;
}
};
int main(){
hhh *h1=new hhh();
h1->cons();
}

q.push(root);复制队列中的root,因此当您执行q.front()=new int(8);时,您正在修改队列中的指针,而不是初始root

所以你的root变量总是NULL的,所以cout<<*root<<endl;给你一个分割错误,因为你不能取消引用空指针。

但除了解释之外,您不应该使用new/delete进行手动分配。C++不像Java或C#,一切都不是参考。