C++核心编程——4.5 运算符重载

本文详细介绍了C++中的运算符重载,包括加法、左移、递增、赋值、关系和函数调用运算符的重载,以及如何在Person和MyInteger类中实现这些操作,同时讨论了运算符重载的注意事项和应用场景。
摘要由CSDN通过智能技术生成

4.5.0 运算符重载概念

   对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型,对应的各类型重载如下表所示。

成员函数重载(写在类内)全局函数重载
加号

Person operator+(const Person& p)

{
        Person temp;
        temp.m_A = this->m_A + p.m_A;
        temp.m_B = this->m_B + p.m_B;
        return temp;
    }

Person operator+(const Person& p1, const Person& p2)

{
Person temp(0, 0);
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
eturn temp;
}

左移无法实现cout在左侧

ostream& operator<<(ostream& cout, Person& p)

{
    cout << "a:" << p.m_A << " b:" << p.m_B;
    return cout;
}

递增前置递增

MyInteger& operator++()

{

 m_Num++;

return *this; 

}//返回引用,否则无法链式编程

Person& operator++(Person p)
{
        p.m_a ++;
        return p;
}

后置递增

MyInteger operator++(int)     //形参占位区分前后置


        MyInteger temp = *this; 
        m_Num++; 
        return temp;  
    }//返回值,返回引用违法

\
赋值

Person& operator=(Person &p)
    {//先判断再赋值
        if (m_Age != NULL)
        {
            delete m_Age;
            m_Age = NULL;
        }
        m_Age = new int(*p.m_Age);
        return *this; 
    }

关系bool operator==(Person & p)
    {
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
函数调用void operator()(string text)
    {
        cout << text << endl;
    }

4.5.1 加号运算符重载

作用:实现两个自定义数据类型相加的运算

class Person {
public:
	Person() {};
	Person(int a, int b)
	{
		this->m_A = a;
		this->m_B = b;
	}
//1.成员函数实现 + 号运算符重载
	Person operator+(const Person& p) {
		Person temp;
		temp.m_A = this->m_A + p.m_A;
		temp.m_B = this->m_B + p.m_B;
		return temp;
	}


public:
	int m_A;
	int m_B;
};

//2.全局函数实现 + 号运算符重载(class+class) 
//Person operator+(const Person& p1, const Person& p2) {
//	Person temp(0, 0);
//	temp.m_A = p1.m_A + p2.m_A;
//	temp.m_B = p1.m_B + p2.m_B;
//	return temp;
//}

//运算符重载 可以发生函数重载 (class+int)
Person operator+(const Person& p2, int val)  
{
	Person temp;
	temp.m_A = p2.m_A + val;
	temp.m_B = p2.m_B + val;
	return temp;
}

void test() {

	Person p1(10, 10);
	Person p2(10, 10);

	//成员函数方式
	Person p3 = p2 + p1;  //成员函数的本质调用 Person p3 = p2.operaor+(p1)
	cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;

    //全局函数方式
	Person p4 = p3 + p2; //全局函数的本质调用 Person p4 = operator+(p3,p2)
	cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
    
    //全局函数重载
    Person p5 = p4 + 10; //全局函数的本质调用 Person p4 = operator+(p4,10)
	cout << "mA:" << p5.m_A << " mB:" << p5.m_B << endl;

}

int main() {

	test();

	system("pause");

	return 0;
}

总结1:对于内置的数据类型的表达式的的运算符是不可能改变的(int/double等的改变不了) 

总结2:不要滥用运算符重载 

4.5.2 左移运算符重载

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

class Person {
	friend ostream& operator<<(ostream& out, Person& p);

public:

	Person(int a, int b)
	{
		this->m_A = a;
		this->m_B = b;
	}
//成员函数:
	//成员函数 void operator<<(Person& p)
    //实现的是 p.operator<<(p),需要两个对象,有一个对象再传入一个对象(错误的)
    
    //若成员函数为 void operator<<(cout) 简化版本为p << cout
    //实现不了   cout<< 不是我们想要的效果
    
    //总结:通常不会用成员函数重载左移运算符(无法实现cout在左侧)
	

private:
	int m_A;
	int m_B;       //通常写一个类的时候把成员属性设置为私有化,又要让全局函数访问,所以用友元
};

//全局函数实现左移重载
// void operator << (cout , p)   该行代码本质为operator << (cout , p) ,简化为cout<<p
//不知道什么返回类型统一先写void

//ostream(output stream:输出流对象)对象只能有一个,所以用引用的方式(不能创建新的)
ostream& operator<<(ostream& cout, Person& p) {
	cout << "a:" << p.m_A << " b:" << p.m_B;
	return cout;
}
//输出要继续用链式编程的方法,必须继续返回ostream,调用之后还返回cout才可以继续链式编程
void test() {

	Person p1(10, 20);

	cout << p1 << "链式编程" << endl; //链式编程
}

int main() {

	test();

	system("pause");

	return 0;
}

总结:重载左移运算符配合友元可以实现输出自定义数据类型  

4.5.3 递增运算符重载

作用: 通过重载递增运算符,实现自己的整型数据

前置递增后置递增
返回类型

返回引用

(返回值无法链式编程)

返回值

(返回引用违法操作)

步骤先++再返回(return *this)

先记录当前值

再++

再返回原来的值

class MyInteger {

	friend ostream& operator<<(ostream& out, MyInteger myint);

public:
	MyInteger() {
		m_Num = 0;
	}
	//前置++
	MyInteger& operator++() {    
//返回值也没有错,但是会返回新的值,在新的值上面进行操作,原来的值只会进行第一次操作
    //返回值:  cout<< ++(++myint) << endl;   输出结果为:2
    //         cout<< myint << endl;                   1(对新对象递增,原对象不变)
    //返回引用:cout<< ++(++myint) << endl;    输出结果为:2
    //         cout<< myint << endl;                   2
		//先++
		m_Num++;
		//再返回
		return *this;   //this指向自身,*this对自身解引用 (返回本身)
        //如果返回的是void,语法变成cout << void,仍然不知道返回的是什么,所以依然需要返回int
	}

	//后置++    
    //(后置递增返回值不返回引用,若后置返回引用,相当于返回的是一个局部的引用,而局部对象在当前函数执行之后就被释放了,如果再返回引用就是违法操作,所以后置递增一定返回的是值)
 MyInteger operator++(int) { //为了发生函数重载必须增加形参int(占位参数,用于区分前置和后置)
		//先返回
		MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
		m_Num++; 
		return temp;   //如果直接return写在前面,函数执行到return就会返回; 
	}

private:
	int m_Num;
};

//重载左移运算符
ostream& operator<<(ostream& cout, MyInteger myint) {
	cout << myint.m_Num;
	return cout;
}


//前置++ 先++ 再返回
void test01() {
	MyInteger myInt;
	cout << ++myInt << endl;
	cout << myInt << endl;
}

//后置++ 先返回 再++
void test02() {

	MyInteger myInt;
	cout << myInt++ << endl;    //后置递增先输出表达式,再++操作
	cout << myInt << endl;
}

int main() {

	test01();
	//test02();

	system("pause");

	return 0;
}

总结: 前置递增返回引用,后置递增返回值  

4.5.4 赋值运算符重载

c++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)

  2. 默认析构函数(无参,函数体为空)

  3. 默认拷贝构造函数,对属性进行值拷贝

  4. 赋值运算符 operator=, 对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

class Person
{
public:

	Person(int age)
	{
		//将年龄数据开辟到堆区,用指针维护堆区的数据
        //关键字new返回的是一个地址
		m_Age = new int(age);
	}

	//重载赋值运算符   重载运算:p2 = p1,当p2去调用函数时需要传入一个p1,所以要传一个person类
	Person& operator=(Person &p)
	{
        //编译器提供的代码是浅拷贝
		//m_Age = p.m_Age;
        
        //深拷贝必须先判断p2本身上面是否有数据,有的话要先置空,再深拷贝
        //要把p1的数据都给p1,但是如果p2本身有数据,就会出错
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}
		
		//提供深拷贝重新new一块空间
		m_Age = new int(*p.m_Age); //用自身的指针指向new的新的地址

		//返回自身
		return *this;  //this是指针,需要解引用才能返回本身
        //返回值如果是void只能进行一次赋值,如果是p3 = p2 = p1,语法上为p3 = void报错
	}


	~Person()
	{
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}
	}

	//年龄的指针
	int *m_Age;

};


void test01()
{
	Person p1(18);

	Person p2(20);

	Person p3(30);

	p3 = p2 = p1; //赋值操作

	cout << "p1的年龄为:" << *p1.m_Age << endl;   //p1.m_Age为指针,所以必须解引用

	cout << "p2的年龄为:" << *p2.m_Age << endl;

	cout << "p3的年龄为:" << *p3.m_Age << endl;
}

int main() {

	test01();

	//int a = 10;
	//int b = 20;
	//int c = 30;

	//c = b = a;
	//cout << "a = " << a << endl;
	//cout << "b = " << b << endl;
	//cout << "c = " << c << endl;

	system("pause");

	return 0;
}

4.5.5 关系运算符重载

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	};

	bool operator==(Person & p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	bool operator!=(Person & p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	string m_Name;
	int m_Age;
};

void test01()
{
	//int a = 0;
	//int b = 0;

	Person a("库里", 18);
	Person b("乔丹", 18);

	if (a == b)
	{
		cout << "a和b相等" << endl;
	}
	else
	{
		cout << "a和b不相等" << endl;
	}

	if (a != b)
	{
		cout << "a和b不相等" << endl;
	}
	else
	{
		cout << "a和b相等" << endl;
	}
}


int main() {

	test01();

	system("pause");

	return 0;
}

4.5.6 函数调用运算符重载

  • 函数调用运算符 “()” 也可以重载

  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数

  • 仿函数没有固定写法,非常灵活

class MyPrint
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}

};

void Print(string text)   //函数
{
		cout << text << endl;
}

void test01()
{
	//重载的()操作符 也称为仿函数
	MyPrint myFunc;
	myFunc("hello world");  //重载的()操作符:使用的方式非常像函数的调用
    Print("hello world");   //函数的调用
}

//仿函数实现非常灵活,实现加法
class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//匿名对象调用(可以不创建对象直接调用) 
    //用MyAdd()创建匿名对象,当前行执行完之后立马被释放
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {

	test01();
	test02();

	system("pause");

	return 0;
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值