Heavy operator <

Source: Internet
Author: User

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:

    1. The input and output operators are generally overloaded as friend functions ,...
    2. 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 <

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.