【发布时间】:2017-08-15 01:50:41
【问题描述】:
我收到分段错误错误。我对 C++ 还很陌生,所以对指针和其他类似的东西不太熟悉。这似乎是一个基本方面,但我似乎无法弄清楚,我已经花了无数个小时。
我有 5 个文件 element.h、element.cpp、heap.h、heap.cpp、main.cpp
线路发生错误
h.setElements(e,i);
Heap.cpp中的函数
我知道这和数组有关
MAIN.CPP
#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;
}
堆.H
#ifndef heap_h
#define heap_h
#include "element.h"
#include <iostream>
using namespace std;
class Heap {
public:
Element* getElements();
void setElements(Element e,int index);
Heap initialize(int n);
void printHeap(Heap heap);
private:
int capacity;
int size;
Element* H;
};
#endif
HEAP.CPP
#include "heap.h"
Heap Heap::initialize(int n){
H = new Element[n];
Heap h;
h.capacity = n;
h.size = 0;
return h;
}
void Heap::printHeap(Heap heap){
for(int i=0;i<heap.capacity;++i){
cout << "Element " << i << " = " << H[i].getKey() << endl;
}
}
void Heap::setCapacity(int nCapacity ) {
capacity = nCapacity;
}
int Heap::getCapacity(void) {
return capacity;
}
void Heap::setSize(int nSize ) {
size = nSize;
}
int Heap::getSize(void) {
return size;
}
Element* Heap::getElements(void){
return H;
}
void Heap::setElements(Element e,int index){
H[index] = e;
}
【问题讨论】:
标签: c++ arrays pointers parameter-passing pass-by-value