2014-07-18 106 views
2

我必須在C++中聲明一個指向數組對象(類)的指針數組。我認爲這是唯一的方法,但顯然我錯了,因爲當我嘗試編譯它時會引發語法錯誤。具體來說,在我收到的7個錯誤中,其中2個錯誤符合要求:我使用「new」創建數組,並在我稱之爲「setData()」的行中創建數組。你能告訴我我哪裏錯了嗎?謝謝。在C++中動態指定一個指向數組的指針數組

#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); 
    } 
} 

回答

3

使用a=new Test*[n];
除此之外,你在你的程序中沒有delete's,瑣碎的getter/setter方法
公共變量是奇怪,*(a+i)可能是a[i]

+0

非常感謝,它工作。但是,你能告訴我在放置星號前後的星號有什麼區別嗎?爲什麼我不能使用*(a + i)(雖然我知道[i]更好),但是? – user1637645

+1

關於'a [i]':你也可以使用其他的東西,但爲什麼?關於星號:語言就是這樣做的;你不能對一切重新排序。對於'new int [10]','[10] new int'或'new [10] int'也會出錯...... – deviantfan

+0

好吧......但是*(a + i) - > setData()會不工作,它會拋出一個錯誤。我不得不使用[i]。 – user1637645

2

你的語法是接近但稍微偏離。使用這個來代替:

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; 
}