【问题标题】:Change array value from another class in C++从 C++ 中的另一个类更改数组值
【发布时间】: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


    【解决方案1】:

    您收到错误是因为 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 对象并返回它? 您可以将初始化方法设为 void,如下所示:

    void Heap::initialize(int n) {
        H = new Element[n];
        capacity = n;
        size = 0;
    }
    

    或者如果你需要返回一个新的 Heap 对象,你可以这样做:

    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
    }
    

    希望这对您有所帮助。

    【讨论】:

    • 哇,谢谢!没有注意到这一点我觉得很愚蠢,我专注于指针,因为我对它们知之甚少
    • 没关系,我们每个人都会遇到:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多