2013-06-24 34 views
-4

我遇到了C++的問題。如何用數組編號類對象

例如我有一個類UNIT。有什麼辦法,在主要以這樣的創建 -

unit[1](int a, int b); 

unit[2]...; 

unit[532]...; 

這將是很容易與這些工作,但我還沒有找到任何辦法使它們與一個數組。請幫忙,謝謝!

+0

你的意思是像['std :: map'](http://en.cppreference.com/w/cpp/container/map)? –

+1

你介意分享真實的問題嗎?也許有更好的方法來解決它。 – freitass

+1

你問如何將類實例放入數組?你喜歡把其他東西放入數組中。 – interjay

回答

2

C++不允許初始化以這種方式數組的元素。爲了初始化數組的元素,你必須在數組被實例化後執行它。

unit units[10]; 
for(int i = 0; i < 10; i++) 
    units[i] = unit(/*params*/); /./ assumes unit has a copy assignment operator 

但是,您可以使用std::vector而不是數組,並用默認值初始化它的元素。我強烈建議使用矢量而不是陣列,因爲它會爲您管理內存資源,可以調整大小並提供諸如管理的元素數量等信息。

std::vector<unit> units(10, unit(/*constructor params*/)); 

下面的例子說明了如何做到這一點,包括具有適當的構造的一個版本的unit。出於您的目的,您可能需要提供複製構造函數和複製賦值運算符。

#include <vector> 
#include <iostream> 

struct unit 
{ 
    int a_; 
    int b_; 

    // constructor 
    unit(int a, int b) : a_(a), b_(b) {} 
}; 

int main() 
{ 
    std::vector<unit> units(10, unit(1, 2)); 

    for(auto i = 0; i < units.size(); ++i) 
    { 
     std::cout 
      << "element[" << i 
      << "] a_ = " << units[i].a_ 
      << " b = " << units[i].b_ 
      << std::endl; 
    } 
} 
0

是,可以改變單元陣列是UNIT *unit[]類型,並調用不同contructors:

class UNIT 
{ 
public: 
    UNIT(){ m_x = 0; } 
    UNIT(int a){ m_x = a; } 
    int m_x; 
}; 

int main() 
{ 
    UNIT* arr[2]; 
    arr[0] = new UNIT(); 
    arr[1] = new UNIT(2); 

    cout<<arr[0]->m_x<<endl;//0 
    cout<<arr[1]->m_x<<endl;//2 
    delete arr[0]; 
    delete arr[1]; 

    return 0; 
} 
+0

您發佈的答案會引起這些錯誤 - 單元[1] =新單元(0,1); 其中[1] =錯誤:期望標識符 和new =錯誤:對於聚合對象預期使用「{....}」進行初始化 – Silverks

+0

檢查更新後的答案。 – Kostia