c++左移运算符重载<<

c++左移运算符重载<<

作用:可以输出自定义类型数据  只能通过全局函数来实现不能通过类成员函数来实现无法使cout在左侧

 1 #include <iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 
 6 
 7 class Persion
 8 {
 9 public:
10     friend ostream& operator<<(ostream& cout, Persion& p1);//保证operator<<()函数能访问到private和proteced权限的成员
11     
12     Persion(string name, int Age,string Sex)
13     {
14         m_Name = name;
15         m_Age = Age;
16         m_Sex = Sex;
17     }
18 private:
19     string m_Name;//姓名
20     int m_Age;//年龄
21     string m_Sex;
22 };
23 //链式编程思想
24  ostream & operator<<(ostream &cout,Persion &p1)//只能通过全局函数实现左移操作符重载,
25 {                                                                    
26      cout << p1.m_Name << "  " << p1.m_Age << "  " << p1.m_Sex;
27      return cout;//返回cout 才能保证cout始终在左边
28 }
29 
30 int main()
31 {
32 
33     Persion p1("张三", 45,"");
34     cout << p1;    //cout << p1  相当于operator<<(cout,p1);
35     cout<< endl;
36 
37     system("pause");
38     return 0;
39 }

 

posted @ 2021-02-17 21:10  两天阿来  阅读(113)  评论(0)    收藏  举报