C++ 更改C+中另一个类的数组值+;
我得到了分割错误。我对C++很陌生,所以不太熟悉指针和其他类似的东西。这似乎是一个基本的方面,但我似乎不明白,我花了无数个小时 我有5个文件element.h、element.cpp、heap.h、heap.cpp和main.cpp 线路上发生错误 h、 集合元素(e,i) 这是Heap.cpp中的一个函数 我知道这和数组有关 MAIN.CPPC++ 更改C+中另一个类的数组值+;,c++,arrays,pointers,parameter-passing,pass-by-value,C++,Arrays,Pointers,Parameter Passing,Pass By Value,我得到了分割错误。我对C++很陌生,所以不太熟悉指针和其他类似的东西。这似乎是一个基本的方面,但我似乎不明白,我花了无数个小时 我有5个文件element.h、element.cpp、heap.h、heap.cpp和main.cpp 线路上发生错误 h、 集合元素(e,i) 这是Heap.cpp中的一个函数 我知道这和数组有关 MAIN.CPP #include <iostream> #include <stdio.h> #include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
#include "element.h"
using namespace std;
int main(){
Heap h;
h = h.initialize(3);
for(int i=0;i<h.getCapacity(); ++i){
Element e;
e.setKey(i);
h.setElements(e,i); // Error occurs here
}
h.printHeap(h);
return 0;
}
#包括
#包括
#包括
#包括“heap.h”
#包括“element.h”
使用名称空间std;
int main(){
堆h;
h=h.初始化(3);
对于(int i=0;i您将得到错误,因为H为null
错误在Heap::initialize(Element,int)方法中。
您正在为调用方法的Heap对象分配局部变量H,而不是返回的对象
Heap Heap::initialize(int n){
H = new Element[n]; // You are assigning H for the current heap object
Heap h; // Here you are creating a new Heap object
h.capacity = n;
h.size = 0;
return h; // You haven't assigned h.H
}
为什么要创建一个新的Heap对象并返回它?
可以将initialize方法设置为void,如下所示:
void Heap::initialize(int n) {
H = new Element[n];
capacity = n;
size = 0;
}
Heap Heap::initialize(int n) {
Heap h;
h.H = new Element[n];
h.capacity = n;
h.size = 0;
return h; // You have assigned h.H
}
或者,如果需要返回一个新的Heap对象,可以这样做:
void Heap::initialize(int n) {
H = new Element[n];
capacity = n;
size = 0;
}
Heap Heap::initialize(int n) {
Heap h;
h.H = new Element[n];
h.capacity = n;
h.size = 0;
return h; // You have assigned h.H
}
希望这对您有所帮助。您得到的错误是因为H为空
错误在Heap::initialize(Element,int)方法中。
您正在为调用方法的Heap对象分配局部变量H,而不是返回的对象
Heap Heap::initialize(int n){
H = new Element[n]; // You are assigning H for the current heap object
Heap h; // Here you are creating a new Heap object
h.capacity = n;
h.size = 0;
return h; // You haven't assigned h.H
}
为什么要创建一个新的Heap对象并返回它?
可以将initialize方法设置为void,如下所示:
void Heap::initialize(int n) {
H = new Element[n];
capacity = n;
size = 0;
}
Heap Heap::initialize(int n) {
Heap h;
h.H = new Element[n];
h.capacity = n;
h.size = 0;
return h; // You have assigned h.H
}
或者,如果需要返回一个新的Heap对象,可以这样做:
void Heap::initialize(int n) {
H = new Element[n];
capacity = n;
size = 0;
}
Heap Heap::initialize(int n) {
Heap h;
h.H = new Element[n];
h.capacity = n;
h.size = 0;
return h; // You have assigned h.H
}
希望这会有帮助。哇,谢谢!我觉得很愚蠢,没有注意到这一点,我把注意力集中在指针上,因为我对指针不太了解。没关系,这发生在我们所有人身上:)哇,谢谢!我觉得很愚蠢,没有注意到这一点,我把注意力集中在指针上,因为我对指针不太了解。没关系,这发生在我们所有人身上:)