When I learned "Deep Exploration", I found that the Code provided in the original article is roughly as follows (3rd pages in the book)
1 class Point3d2 {3 inline ostream&4 operator <<(ostream& os, const Porint3d &pt)5 {6 ...7 } 8 };
It cannot be compiled (G ++ ). Actually, the compile _ compiler is a bit difficult. I thought it was possible to compile it. Actually, practice is the only criterion for verifying truth. A bunch of queries on the Internet found that there are roughly two types of statements:
- The input and output operators are generally overloaded as friend functions ,...
- Binary operators can be reloaded as friend functions or member functions ,...
I can't help but wonder why. I didn't have to say when or when. Okay, come on.
1 #include <iostream> 2 using namespace std; 3 4 class Point3d 5 { 6 private: 7 double x; 8 double y; 9 double z;10 public:11 Point3d(double tx, double ty, double tz);12 13 friend ostream&14 operator <<(ostream& os, const Point3d &pt);15 16 inline ostream&17 operator <<(ostream& os)18 {19 os<<"inline method, "<<"x: "<<x<<", y: "<<y<<", z: "<<z;20 return os;21 }22 };23 24 ostream&25 operator <<(ostream& os, const Point3d &pt)26 {27 os<<"friend method, "<<"x: "<<pt.x<<", y: "<<pt.y<<", z: "<<pt.z;28 return os;29 }30 31 Point3d::Point3d(double tx, double ty, double tz)32 {33 x=tx;34 y=ty;35 z=tz;36 }37 38 int main(void)39 {40 Point3d a(1,2,3);41 cout<<a<<endl;42 a<<cout<<endl;43 }
Looking at the proud look of the 42nd lines of code, I can only kneel down. The output result is as follows:
1 friend method, x: 1, y: 2, z: 32 inline method, x: 1, y: 2, z: 3
In a single sentence, the input operator >>and the output operator <, can be a member of a friend.
Heavy operator <