左移运算符重载(2)

作用:可以输出自定义数据类型

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Person
 5 {
 6 public:
 7 
 8     //成员函数重载左移运算符 p.operator<<(cout)  简化  p << cout 我们想要 cout << p
 9     //所以无法使用成员函数来重载<<运算符,因为无法实 cout 在左边
10     /*void operator<<(Person &p)
11     {
12 
13     }*/
14 
15     int m_A;
16     int m_B;
17 };
18 
19 //只能用全局函数重载左移运算符 operator<<(cout,p)  简化  cout << p; 
20 void operator<<(ostream &cout,Person &p)
21 {
22     cout << "m_A= " << p.m_A << " m_B= " << p.m_B;
23 }
24 
25 void test_01(void)
26 {
27     Person p;
28     p.m_A = 10;
29     p.m_B = 10;
30 
31     cout << p;
32 }
33 
34 int main(void)
35 {
36     test_01();
37 
38     system("pause");
39     return 0;
40 }

因为重载了左移运算符,所以就不能够在后面加上换行运算符 endl 。如果想要换行,所以重载左移运算符函数还需要返回cout。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Person
 5 {
 6 public:
 7 
 8     //成员函数重载左移运算符 p.operator<<(cout)    简化        p << cout 我们想要 cout << p
 9     //所以无法使用成员函数来重载<<运算符,因为无法实 cout 在左边
10     /*void operator<<(Person &p)
11     {
12 
13     }*/
14 
15     int m_A;
16     int m_B;
17 };
18 
19 //只能用全局函数重载左移运算符     operator<<(cout,p)        简化        cout << p; 
20 ostream & operator<<(ostream &cout,Person &p)
21 {
22     cout << "m_A= " << p.m_A << " m_B= " << p.m_B;
23     return cout;
24 }
25 
26 void test_01(void)
27 {
28     Person p;
29     p.m_A = 10;
30     p.m_B = 10;
31 
32     cout << p << "Hello,world!" << endl;//链式编程思想
33     //cout << p << endl;//
34 }
35 
36 int main(void)
37 {
38     test_01();
39 
40     system("pause");
41     return 0;
42 }

我们通常将成员的属性私有化,私有化之后的代码为:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Person
 5 {
 6     friend ostream & operator<<(ostream &cout, Person &p);//通过友元技术访问
 7 public:
 8 
 9     //成员函数重载左移运算符 p.operator<<(cout)  简化  p << cout 我们想要 cout << p
10     //所以无法使用成员函数来重载<<运算符,因为无法实 cout 在左边
11     /*void operator<<(Person &p)
12     {
13 
14     }*/
15 
16     Person(int a, int b)
17     {
18         m_A = a;
19         m_B = b;
20     }
21 
22 private:
23     int m_A;
24     int m_B;
25 };
26 
27 //只能用全局函数重载左移运算符 operator<<(cout,p) 简化 cout << p; 
28 ostream & operator<<(ostream &cout,Person &p)
29 {
30     cout << "m_A= " << p.m_A << " m_B= " << p.m_B;
31     return cout;
32 }
33 
34 void test_01(void)
35 {
36     Person p(10,10);
37 
38     cout << p << " Hello,world!" << endl;//链式编程思想
39     //cout << p << endl;//
40 }
41 
42 int main(void)
43 {
44     test_01();
45 
46     system("pause");
47     return 0;
48 }

猜你喜欢

转载自www.cnblogs.com/huanian/p/12763622.html