# day-02 类和对象–C++运算符重载--左移运算符重载

类和对象–C++运算符重载

C++ 预定义的运算符,只能用于基本数据类型的运算,不能用于对象的运算
如何使运算符能用于对象之间的运算呢

左移运算符重载

作用:可以输出自定义数据类型 cout << 对象及内部属性 <<endl;

1.一般方法

代码:

#include <iostream>
using namespace std;

class Person {
    
    
public:
	int m_A;
	int m_B;
};

void test(){
    
    
	Person p;
	p.m_A=10;
	p.m_B=10;
	cout << "p.m_A= "<< p.m_A << endl;
	cout << "p.m_B= "<< p.m_B << endl;
	}

int main(){
    
    
	test();
	system("pause");
	return 0;
	}

运行结果:
在这里插入图片描述

2.成员函数实现左移运算符重载(成员函数写在类内)

p.operator<<(cout)可以简化为 p << cout
但我们需要不是我们想要的效果 cout<<p
首先有个Person对象去调用成员函数,这样子p就已经在左边了,无法实现cout在左边
所以 无法利用成员函数实现左移运算符的重载

3.全局函数实现 左移运算符重载(全局函数写在类外)

回顾:

Person p3 =p2+p1; //相当于p2.operator+(p1);
同理得 operator <<(cout ,p) ->cout<<p;

代码:

#include <iostream>
using namespace std;

class Person {
    
    
public:
	int m_A;
	int m_B;
};

void operator<<(ostream &cout, Person &p) {
    
    
	cout << "m_A = " << p.m_A << "  m_B = " << p.m_B;
}

void test(){
    
    
	Person p;
	p.m_A = 10;
	p.m_B = 10;
	cout << p; 
}

int main() {
    
    
	test();
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

4.实现换行

但是若加endl换行,则会报错。因为这是一个链式编程的语法,如果我们返回void,则不符合链式编程的思想,所以为什么我们运算符重载的函数需要返回一个ostream类对象(通过右键cout,选择定义看到cout是ostream的一个输出流对象。函数的第一个参数 ostream &cout) 因为运行代码中,只能有一个cout对象,所以这里使用&cout(引用的方式),保证全局只有一个该对象。

代码:

#include <iostream>
using namespace std;

class Person {
    
    
public:
	int m_A;
	int m_B;
};

ostream & operator<<(ostream &cout, Person &p) {
    
    
	cout << "m_A = " << p.m_A << "  m_B = " << p.m_B;
	return cout;
}

void test(){
    
    
	Person p;
	p.m_A = 10;
	p.m_B = 10;
	cout << p << endl;
}

int main() {
    
    
	test();
	system("pause");
	return 0;
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48245161/article/details/113011054