标签:style blog color io os sp div on log
学习《深入探索》时,发现原文中提供的一个代码大致如下(书中第3页)
1 class Point3d 2 { 3 inline ostream& 4 operator <<(ostream& os, const Porint3d &pt) 5 { 6 ... 7 } 8 };
竟然编译不过(g++)。╮(╯_╰)╭实在有点坑啊,天真的我以为都是可以编译过的,果然实践是检验真理的唯一标准。网上一堆查,发现大致有两种说法:
不免疑惑,怎么个情况啊,没具体说什么时候可以,什么时候不可以啊。好吧,自己来吧。
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 }
看着第42行代码那傲娇的样子,我只能给跪了。输出结果如下:
1 friend method, x: 1, y: 2, z: 3 2 inline method, x: 1, y: 2, z: 3
总之一句话,输入运算符>>,输出运算符<<,可以成员可以友元。
标签:style blog color io os sp div on log
原文地址:http://www.cnblogs.com/warnet/p/4015492.html