簡體   English   中英

在C ++中動態聲明一個指向對象的指針數組

[英]Declaring an array of pointers to objects dynamically in C++

我必須聲明一個指向C ++中(類的)對象的指針的數組。 我以為這是唯一的方法,但是顯然我錯了,因為在嘗試編譯它時會引發語法錯誤。 具體來說,在收到的7個錯誤中,有2個錯誤出現在以下行中:我使用“ new”創建數組的地方,以及我調用“ setData()”函數的行。 你能告訴我我哪里出問題了嗎? 謝謝。

#include <iostream>

class Test
{
    public:
        int x;

        Test() { x=0; }
        void setData(int n) { x=n; }
};

void main()
{
    int n;
    Test **a;

    cin >> n;
    a=new *Test[n];

    for(int i=0; i<n; i++)
    {
        *(a+i)=new Test();
        *(a+i)->setData(i*3);
    }
}

使用a=new Test*[n];
除此之外,您的程序中沒有刪除,瑣碎的getter / setter
因為公共變量很奇怪,並且*(a+i)可能是a[i]

您的語法接近,但略有偏離。 使用此代替:

Test **a;

...

a=new Test*[n];

for(int i=0; i<n; i++)
{
    a[i]=new Test();
    a[i]->setData(i*3);
}

...

// don't forget to free the memory when finished...

for(int i=0; i<n; i++)
{
    delete a[i];
}

delete[] a;

由於您使用的是C ++,因此應該改用std::vector 我還建議將所需的值傳遞給類構造函數:

#include <iostream>
#include <vector>

class Test
{
    public:
        int x;

        Test(int n = 0) : x(n) { }
        Test(const Test &t) : x(t.x) { }
        void setData(int n) { x=n; }
};

int main()
{
    int n;
    std::vector<Test> a;

    cin >> n;
    a.reserve(n);

    for(int i=0; i<n; i++)
    {
        a.push_back(Test(i*3));
    }

    ...

    // memory is freed automatically when finished...

    return 0;
}

暫無
暫無

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

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