C++ //左移运算符重载

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 class Person
 6 {
 7     friend ostream& operator<<(ostream& cout, Person& p);
 8 public:
 9     Person(int a, int b)
10     {
11         m_A = a;
12         m_B = b;
13     }
14 //public:
15     //利用成员函数 重载 左移运算符
16     //不会利用成员函数重载<<运算符,因为无法实现cout 在左侧
17     //void operator<<(cout)     //p.operator<<(cout) 简化:p<<cout
18     //{
19 
20     //}
21 private:
22     int m_A;
23     int m_B;
24 };
25 
26 //只能利用全局函数重载左移运算符  
27 //cout  输出流  ostream
28 
29 ostream & operator<<(ostream &cout,Person &p) //本质 operator <<(cout,p) 简化 cout << p
30 {
31     cout << "m_A= " << p.m_A << "  m_B = " << p.m_B;
32     return cout;
33 }
34 
35 void test01()
36 {
37     Person p(10,50);
38     //p.m_A = 10;
39     //p.m_B = 10;
40 
41     cout << p << endl;
42 }

posted on 2021-08-07 14:34  Bytezero!  阅读(69)  评论(0编辑  收藏  举报