2011-05-26 30 views
8

का उपयोग कर structs के एक सदस्य सरणी का आवंटन अगर मैं है:सी ++: गतिशील रूप से गैर-डिफ़ॉल्ट निर्माता

struct a_struct 
{ 
    int an_int; 

    a_struct(int f) : an_int(f) {} 
    a_struct() : an_int(0) {} 
}; 

class a_class 
{ 
    a_struct * my_structs; 

    a_class() {...} 
}; 

मैं कर सकते हैं:

a_class() {my_structs = new a_struct(1)} 
//or 
a_class() {my_structs = new a_struct [10]} 

लेकिन मैं ऐसा नहीं कर सकते हैं:

a_class() {my_structs = new a_struct(1) [10]} 
//or 
a_class() {my_structs = new a_struct() [10]} 

इस काम करने के लिए प्राप्त करने के लिए किसी भी सही सिंटैक्स है? या चारों ओर एक आसान काम?

उत्तर

5

तो एसटीएल का उपयोग कर एक विकल्प है, तो आप std :: वेक्टर के बजाय एक गतिशील सरणी के इस्तेमाल कर सकते हैं।

मुझे लगता है कि है कि इस काम करेगा:

std::vector<a_struct> my_structs; 

my_structs.assign(10, 1); 

यदि नहीं, तो इस कार्य करना चाहिए:

my_structs.assign(10, a_struct(1)); 
+2

या सिर्फ 'std :: वेक्टर my_structs (10, 1); ' – Nemo

0

आप संकेत की ओर इशारा की एक सरणी इस्तेमाल कर सकते हैं। तो फिर तुम सरणी कि संकेत a_struct करने के लिए() का आयोजन करेगा बना सकते हैं, ताकि आप बाद में तय कर सकते हैं जो निर्माता का उपयोग करें:

class a_class { 
    a_struct ** my_structs; 

    a_class() { my_structs = new a_struct* [10]} 
    void foo() { 
     my_structs[0] = new a_struct(1); 
     my_structs[5] = new a_struct("some string and float constructor", 3.14); 
    } 
}; 
+0

यह आपको तो struct करने के लिए (structs की एक सरणी या सूचक के आसपास पारित सरणी के अगले तत्व को स्थानांतरित करने के लिए सूचक गणित का उपयोग करने की अनुमति नहीं है)। – iheanyi

0

आप किसी विशेष पैरामिट्रीकृत निर्माता पर सीधे यह नहीं कर सकते। हालांकि आप कर सकते हैं,

a_struct *my_struct[10] = {}; // create an array of pointers 

for (int i = 0; i < 10; i++) 
    my_struct[i] = new a_struct(i); // allocate using non-default constructor 

आप स्मृति को डी-आवंटित करने के लिए,

for (int i = 0; i < 10; i++) 
    delete my_struct[i] // de-allocate memory 

मैं एक std::vector कंटेनर उपयोग करने का सुझाव के बजाय इस प्रक्रिया से गुजर रही जा रहे है।

+1

इस मामले में 'std :: vector' का लाभ यह है कि सभी 'my_struct' एक संगत स्मृति ब्लॉक में होंगे। – Xeo

+0

यह आपको structs की एक सरणी (या संरचना के सूचक के लिए पास करने की अनुमति नहीं देता है, फिर सरणी के अगले तत्व पर जाने के लिए पॉइंटर गणित का उपयोग करें) – iheanyi

3

आप स्मृति का एक कच्चे हिस्सा आवंटित और प्रत्येक struct प्रारंभ करने में नियुक्ति नई इस्तेमाल कर सकते हैं: भी

int number_of_structs = 10; 
my_structs = (a_struct*)new unsigned char[sizeof(a_struct) * number_of_structs]; 
    // allocate a raw chunk of memory 
a_struct* p = m_structs; 
for (int i=0; i<number_of_structs; i++) 
{ 
    new (p) a_struct(i); 
    p++; 
} 

देखें: What uses are there for "placement new"?

संबंधित मुद्दे