class Node{
private:
string name;
Node** adjacent;
int adjNum;
public:
Node();
Node(string, int adj_num);
Node(const Node &);
bool addAdjacent(const Node &);
Node** getAdjacents();
string getName();
~Node();
};
bool Node::addAdjacent(const Node &anode){
Node** temp;
temp= new Node*[adjNum+1];
for(int i=0;i<adjNum+1;i++)
temp[i]=adjacent[i];
temp[adjNum]=const_cast<Node *>(&anode);
delete[] adjacent;
adjacent=new Node*[adjNum+1];
adjacent=temp;
delete[] temp;
adjNum++;
return true;
}
int main()
{
Node node1("A",0);
Node node2("B",0);
node1.getName();
node1.addAdjacent(node2);
system("PAUSE");
return 0;
}
当程序涉及到这一部分时:
for(int i=0;i<adjNum+1;i++)
temp[i]=adjacent[i];
它说访问冲突读取位置0xcccccccc。该类必须在相邻位置分配内存,但是我认为这不能解决这个问题吗?
最佳答案
adjacent=new Node*[adjNum+1];
adjacent=temp;
delete[] temp;
这看起来像个错误。您可能打算写:
adjacent = temp;
就是这样。
另外,我认为问题在于
for(int i=0;i<adjNum+1;i++)
您正在复制
adjNum+1
元素,即使(我假设)adjacent
仅包含adjNum
元素。从+1
循环中删除for
。