an array of object in C++ is based on two different concepts such as an array of structure, the concept follows,
C ++ में array of structure in C++ and array of object दोनों लगभग समान हैं।
array of object में, array का हरेक element object बन जाता है, जिसका अर्थ है कि C ++ में array of object उसी same class के objects का collection होता है।
array of object important है जैसे आप 10 student के record store करना चाहते हैं, तो आपको प्रत्येक student के लिए 10 object declare करने की आवश्यकता नहीं है। आप class object को ही एक array type object बना सकते हैं और array size 10 कर सकते हैं। यहाँ पर object name तो समान होगा लेकिन index value अलग होने के कारण object भी different होंगे।
इसे आप नीचे दिए गए program से समझ सकते हैं –
और हम जानते हैं कि एक object collection of data member and function member का collection होता है,
आइए इसे एक program में देखें, जहां हम 2 student record store करते हैं-
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class student
{
// public member by default
int roll_no;
char name[20];
public: // public member declaration
void get_record(void);
void show_record(void);
};
void student::get_record() // get record by user
{
cout<<"\nEnter roll no: ";
cin>>roll_no;
cout<<"Enter Name : ";
gets(name);
}
void student::show_record() // display record
{
cout<<"\nRoll no: "<<roll_no;
cout<<"\nName : "<<name;
}
void main() // main function
{
clrscr();
student obj[2]; // 2 students
for(int i=0; i<2; i++)
{
cout<<"Enter "<<i+1<<" student record: ";
obj[i].get_record();
}
for(int j=0; j<2; j++)
{
cout<<"\ndisplay "<<j+1<<" student record: ";
obj[j].show_record();
}
getch();
}
हम loop के बजाय निम्न statements का भी उपयोग कर सकते थे परन्तु यह केवल 1 -2 statement तक ही सही होगा-
student obj[2];
obj[0].get_record(); //1st student
obj[0].get_record(); //2nd student
obj[1].show_record(); //1st student
obj[1].show_record(); //2nd student
जबकि statement बढ़ने पर हमें loop का प्रयोग करना होगा।
यह program निम्नलिखित output देगा-
OUTPUT:-
Enter 1 student record:
Enter roll no: 11
Enter Name : Rahul sherma
Enter 2 student record:
Enter roll no: 12
Enter Name : Rakesh sherma
DIsplay 1 student record:
Roll no: 11
Name : Rahul sherma
DIsplay 2 student record:
Roll no: 12
Name : Rakesh sherma
Explanation:-
यदि आप 10 students को store करना चाहते हैं , तो array size 10 declare करना होगा।
इसका एक अच्छा उदाहरण यहाँ दिया गया है।
Did you notice
array of object में , हमने student record को store करने के लिए static memory allocation का उपयोग किया है, लेकिन इसमें हम dynamic memory allocate कर सकते हैंजिससे memory waste नहीं होगा।
more about the array of object
previous- class and object in C++
next- friend function in C++