簡體   English   中英

在 C++ 中使用指向對象的指針數組

[英]Using array of pointers to object in C++

我需要將對象保存為動態數組中的指針,但我有問題。 這是我的代碼,有三個類,我需要有指向第二類的指針數組 (arrayoftwo),這樣可以進一步與第三類一起工作,依此類推。 我有兩個問題。 一個是我無法弄清楚如何為我的 arrayoftwo 動態分配空間(我需要根據存儲的指針數量動態調整大小),第二個問題是如何在不破壞對象本身的情況下准確存儲指向對象的指針。 這是我的代碼:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;

class One {
public:
    bool addTwo(int a);

private:
    void getspace(void);
    class Two {
    public:
        int a;
    private:

        class Three {
            /*...*/
        };
        Three arrayofThree[];

    };
    int freeindex;
    int allocated;
    Two *arrayoftwo[];
};

void One::getspace(void){
    // how to allocate space for array of pointers ?
    arrayoftwo=new *Two[100];
    allocated=100;
}
bool One::addTwo(int a){
    Two temp;
    temp.a=a;
    getspace();
    arrayoftwo[freeindex]=&temp;
    freeindex++;
    return true;
    //after leaving this method, will the object temp still exist or pointer stored in array would be pointing on nothing ?
}

int main() {
    bool status;
    One x;
    status = x . addTwo(100);
    return 0;
}

感謝您的任何幫助。

編輯:我不能使用矢量或任何其他高級容器

離開addTwotemp將不存在; 您存儲到它的指針此時無效。 不是將對象存儲為局部變量,而是使用 new 在堆上分配它:

  Two* temp = new Two();

分配指針數組:

  Two** arrayoftwo;  // declare it like this
  // ...
  arrayoftwo = new Two*[100];

並且getspace應該傳遞a (來自addTwo )或a應該存儲為allocated的成員變量並且getspace應該從那里訪問它。 否則它假設100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM