Archived

This topic is now archived and is closed to further replies.

doublin_ken

operator overloading

Recommended Posts

I can overloading >> << without non-string value. But when I add the string in private that will cause some unknown problem I don''t know whether is my >> format is wrong or other question. Anyone can advice. #include <iostream.h> #include <string.h> class Complex { public: Complex(float re, float im, char* txt) : myReal(re), myImag(im) , str(txt) {} friend istream& operator>>(istream&, Complex&); friend ostream& operator<<(ostream&, const Complex&); private: float myReal; float myImag; char* str; }; istream& operator>>(istream& in, Complex& c) { double real, imag; char* txt = " "; in >> real >> imag >> txt; if (in.good()) { c.myReal = (float)real; c.myImag = (float)imag; c.str = txt; } return in; } ostream& operator<<(ostream& out, const Complex& c) { out << "(" << c.myReal << "," << c.myImag << ")" << c.str << " " << endl; return out; } void main() { Complex temp(0.0, 0.0, "bb"); //cout << " input two float and one string: " << endl; //cin >> temp; //drop before comment will //cause quiz cout << temp; }

Share this post


Link to post
Share on other sites
Use <iostream> (and/or <fstream> instead of <iostream.h> (and/or <fstream.h> if you want to do any kind of serious work on streams.

The C++ committee deprecated <iostream.h> in Dec 1997. It must not be used in new programs.

Change that part, deal with the namespace issues (using namespace std; or explicit std:: scoping), then we''ll talk.

Additionally, C++ also provides a <string> header with a C++ std::string class. And the C header <string.h> has been superceded by <cstring>. No C++ header has a .h extension (except C compatibility headers).

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

Share this post


Link to post
Share on other sites
Additional notes about your C string: assigning a pointer does not a copy of the string make, and pointing to a local variable creates a dangling pointer when the local goes out of scope.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

Share this post


Link to post
Share on other sites