不要随意乱用符号重载

内置数据类型 的运算符不可以重载

cout << 直接对Person自定义数据类型 进行输出

 写到全局函数中 ostream& operator<< ( ostream & cout, Person & p1  ) {}

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Person
{
    friend ostream& operator<<(ostream & cout, Person &p);    //重载左移运算符做友元函数
public:
    Person(int a, int b) :m_A(a), m_B(b)
    {

    }
private:
    int m_A;
    int m_B;
};

ostream& operator<<(ostream & cout, Person &p)    //重载左移运算符不可以写到成员函数中 保证全局只有一个cout 所以传值要用引用
{
    cout << "p.m_A=" << p.m_A << ",p.m_B=" << p.m_B;
    return cout;
}
void test()
{
    Person p1(10, 20);
    cout << p1 << endl;
}

int main()
{
    test();
    system("Pause");        //阻塞功能
    return EXIT_SUCCESS;    // 返回正常退出
}

结果:

重载左移运算符并作为友元函数

 

相关文章:

  • 2022-12-23
  • 2022-01-02
  • 2022-12-23
  • 2021-07-17
  • 2022-12-23
  • 2021-11-08
  • 2021-11-06
  • 2022-12-23
猜你喜欢
  • 2021-11-26
  • 2021-11-24
  • 2022-12-23
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案