"Roy Varghese" <rv*******@usersDOTsf.net> wrote in message
news:OWYyb.279447$275.998391@attbi_s53...
Shailesh wrote: Hi!
<snip>
ostream& operator << ( ostream &output, const MyClass &m )
{
output << "------------------------BEGIN -------------------------" <<
endl
<< endl
<< "X: " << m.x << endl
<< "Y: " << m.y << endl
<< "Num of Elements : "<<m.num_elems<< endl
<<"Elements : "
<<<<<<<<<<<<<<????How can I print Array>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<< "------------------------- END
--------------------------" << endl;
return output;
}
One of many ways:
struct MyClass {
string data;
};
ostream& operator<<(ostream& os, pair<int,MyClass> intmc) {
os << "Number=" << intmc.first << " MyClass=" <<
intmc.second.data << endl;
return os;
}
int main() {
MyClass mc1;
int num;
cin >> num;
mc1.data = "Hello world";
cout << pair<int,MyClass>(num,mc1);
}
--
Hi Roy,
probably I overlooked something but I can't quite see how this would help
the OP to print an array.
To the OP:
If you the number of elements that you want to print is stored in num_elems
then you can just iterate over your array. For example:
ostream& operator << ( ostream &output, const MyClass &m )
{
output << "------------------------BEGIN -------------------------" <<
endl << endl
<< "X: " << m.x << endl
<< "Y: " << m.y << endl
<< "Num of Elements : "<<m.num_elems<< endl <<"Elements : " <<
endl;
// print elements
for( int i = 0< i < m.num_elems; ++i ) {
output << elem_array[i] << endl;
}
output << "------------------------- END --------------------------" <<
endl;
return output;
}
Just some other remarks - as you have a dynamically allocated array in your
class you should take care of copy ctor & the assignment operator, which you
probably did. As it's not indicated in the code snippet you provided I just
wanted to remark on this. Furthermore for safety & comfort you might
consider using a vector class instead of the array.
Regards
Chris