Advertisement

operator overloading

Started by October 17, 2002 09:03 PM
1 comment, last by doublin_ken 22 years, 1 month ago
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; }
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 ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
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 ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement