2-7 类与对象:C++运算符重载

目录

一、加号运算符重载

1. 加法重载可以通过全局函数实现

2. 加法重载可以通过类成员函数实现

二、左移运算符重载

三、递增运算符重载

四、赋值运算符重载

五、关系运算符重载

六、函数调用运算符重载


运算符重载是对已有运算符进行重新定义,赋予其新的功能,使其适应不同数据类型。

一、加号运算符重载

实现两个自定义数据类型的加法运算。

1. 加法重载可以通过全局函数实现

#include <iostream>
using namespace std;
#include<string>

class Student {
	//友元声明
	friend void test();
	friend Student operator+(Student &S1, Student &S2);
public:
	//构造函数
	Student() {}

	//析构函数
	~Student() {}

private:
	int m_A;
	int m_B;
};

Student operator+(Student &S1, Student &S2) {  //全局函数实现加法重载
	Student temp;
	temp.m_A = S1.m_A + S2.m_A;
	temp.m_B = S1.m_B + S2.m_B;
	return temp;
}

void test() {
	Student S1;
	S1.m_A = 10;
	S1.m_B = 10;
	Student S2;
	S2.m_A = 15;
	S2.m_B = 20;
	Student S3 = S1 + S2;  // 等价于 Student S3 = operator+(S1,S2);
	cout << "S3的成员变量m_A的值为:" << S3.m_A << endl;
	cout << "S3的成员变量m_B的值为:" << S3.m_B << endl;
}

int main() {
	test();
	system("pause");
	return 0;
}
S3的成员变量m_A的值为:25
S3的成员变量m_B的值为:30
请按任意键继续. . .

2. 加法重载可以通过类成员函数实现

#include <iostream>
using namespace std;
#include<string>

class Student {
	//友元声明
	friend void test();  
public:
	//构造函数
	Student(){}

	//析构函数
	~Student(){}

	//类加法重定义
	Student operator+(Student &S) {  //类内成员函数实现加法重载
		Student temp;
		temp.m_A = this->m_A + S.m_A;
		temp.m_B = this->m_B + S.m_B;
		return temp;
	}

private:
	int m_A;
	int m_B;
};

void test() {
	Student S1;
	S1.m_A = 10;
	S1.m_B = 10;
	Student S2;
	S2.m_A = 15;
	S2.m_B = 20;
	//使用类内成员函数实现的加法重载实现类的加法
	Student S3 = S1 + S2;  // 等价于 Student S3 = S1.operator+(S2);
	cout << "S3的成员变量m_A的值为:" << S3.m_A << endl;
	cout << "S3的成员变量m_B的值为:" << S3.m_B << endl;
}

int main() {
	test();
	system("pause");
	return 0;
}
S3的成员变量m_A的值为:25
S3的成员变量m_B的值为:30
请按任意键继续. . .

二、左移运算符重载

通过左移运算符重载,可以实现自定义数据类型的输出。

#include <iostream>
using namespace std;
#include<string>

class Student {
	//友元声明
	friend ostream& operator<< (ostream &cout, Student &S);
	
public:
	//构造函数
	Student(int A, int B):m_A(A),m_B(B) {}

	//析构函数
	~Student() {}

private:
	int m_A;
	int m_B;
};


//全局函数实现左移运算符的重载
ostream& operator<< (ostream &cout, Student &S) { //cout是类ostream的一个实例化,且只能有一个,因此在返回时使用其引用
	cout << "m_A = " << S.m_A << endl;
	cout << "m_B = " << S.m_B << endl;
	return cout;
}

void test() {
	Student S(10, 20);
	cout << S << endl;
}

int main() {
	test();
	system("pause");
	return 0;
}
m_A = 10
m_B = 20

请按任意键继续. . .

注:左移运算符一般不通过类成员函数实现重载,因为在类内无法将cout放在左移运算符的左侧。

class Student{
public:
    ostream& operator<<(ostream &cout){ //无法实现左移运算符的重载
        cout << age << endl;
        return cout;
    }
private:
    int age;
}

三、递增运算符重载

对递增(++)和递减(--)运算符进行重载,使其可以直接作用于类(操作的类的成员变量必须为整型int)。

注:

  • 前置递增或递减返回类型为类的引用,后置递增或递减返回类型为类的值传递方式
  • 由于返回值类型不能作为函数重载条件,因此使用占位参数int来区分前置运算和后置运算,其中有占位参数int的为后置运算
#include <iostream>
using namespace std;
#include<string>

class MyInt {
	//友元声明
	friend ostream & operator<<(ostream &cout, MyInt &I);
public:
	//构造函数
	MyInt(int Int) {
		m_Int = Int;
	}

	//前置++
	MyInt & operator++() {
		m_Int++;
		return *this;
	}
	//后置++
	MyInt operator++(int) {  //使用占位参数int来与前置操作区分,使函数满足重载条件
		MyInt temp = *this;
		m_Int++;
		return temp;
	}
	//前置--
	MyInt & operator--() {
		m_Int--;
		return *this;
	}
	//后置--
	MyInt operator--(int) {
		MyInt temp = *this;
		m_Int--;
		return temp;
	}

private:
	int m_Int;
};

//左移运算符的重载,使其能够直接打印类
ostream & operator<<(ostream &cout, MyInt &I) {
	cout << I.m_Int;
	return cout;
}


void test() {
	MyInt m_I(10);
	cout << "操作前为10,类后置++后的打印结果:" << m_I++ << endl;
	cout << "操作前为11,类前置++后的打印结果:" << ++m_I << endl;
	cout << "操作前为12,类后置--后的打印结果:" << m_I-- << endl;
	cout << "操作前为11,类前置--后的打印结果:" << --m_I << endl;

}

int main() {
	test();
	system("pause");
	return 0;
}
操作前为10,类后置++后的打印结果:10
操作前为11,类前置++后的打印结果:12
操作前为12,类后置--后的打印结果:12
操作前为11,类前置--后的打印结果:10
请按任意键继续. . .

四、赋值运算符重载

C++至少会给一个类添加4个函数:

  • 默认构造函数,无参空函数
  • 默认析构函数,无参空函数
  • 默认拷贝构造函数,对属性进行值拷贝
  • 赋值运算符 operator=,对属性进行值拷贝

与值拷贝构造函数一样,若类内有属性存储于堆区,将出现浅拷贝的问题(重复释放堆区内存)。

#include <iostream>
using namespace std;
#include<string>

class Student {
	//友元声明
	friend ostream & operator<<(ostream &cout, Student &S);
public:
	//构造函数
	Student(int age, int score) {
		m_Age = new int(age);  //使用堆区内存存放年龄
		m_Score = score;
	}
	//析构函数
	~Student() {
		if(m_Age != NULL) {
			delete m_Age;
			m_Age = NULL;
		}
	}
	//赋值运算符重载
	Student & operator=(Student &S) {
		if (m_Age != NULL) {
			delete m_Age;
			m_Age = NULL;
		}
		m_Age = new int(*S.m_Age); //深拷贝
		m_Score = S.m_Score;
		return *this;
	}

private:
	int * m_Age;
	int m_Score;
};

//左移运算符的重载,使其能够直接打印类
ostream & operator<<(ostream &cout, Student &S) {
	cout << "年龄为:" << *S.m_Age << "\t分数为:" << S.m_Score;
	return cout;
}


void test() {
	Student S1(10,99);
	cout << "S1的值:" << S1 << endl;
	// Student S2 = S1; //会调用默认值拷贝构造函数,产生堆区内存重复释放问题
	Student S2(28, 85);
	cout << "调用赋值重载函数前S2的值:" << S2 << endl;
	S2 = S1;  //调用赋值重载函数,等价于 S2 = operator=(S1);
	cout << "调用赋值重载函数后S2的值:" << S2 << endl;
}

int main() {
	test();
	system("pause");
	return 0;
}
S1的值:年龄为:10      分数为:99
调用赋值重载函数前S2的值:年龄为:28    分数为:85
调用赋值重载函数后S2的值:年龄为:10    分数为:99
请按任意键继续. . .

五、关系运算符重载

对==、!=、>、<、>=、<=等关系运算符进行重载,使其能够判断自定义数据类型。

#include <iostream>
using namespace std;
#include<string>

class Student {
public:
	//构造函数
	Student(int age, int score) {
		m_Age = age;  //使用堆区内存存放年龄
		m_Score = score;
	}
	//析构函数
	~Student() {
		
	}
	//赋值运算符重载
	bool operator==(Student &S) {
		if (m_Age == S.m_Age && m_Score == S.m_Score)
			return true;
		return false;
	}

private:
	int m_Age;
	int m_Score;
};


void test() {
	Student S1(10,99);
	Student S2(28, 85);
	if (S1 == S2) {
		cout << "S1与S2相同。" << endl;
	}
	else{
		cout << "S1与S2不相同。" << endl;
	}
}

int main() {
	test();
	system("pause");
	return 0;
}
S1与S2不相同。
请按任意键继续. . .

六、函数调用运算符重载

  • 函数调用运算符()可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活
#include <iostream>
using namespace std;
#include<string>

class MyAdd {
public:
	int operator()(int num1, int num2) {  //重载函数调用运算符()
		return num1 + num2;
	}
};


void test() {
	MyAdd add;
	int res = add(3, 4);  //调用重载的函数调用运算符().与调用函数非常像,因此称为仿函数
	cout << res << endl;
	//创建匿名函数对象
	cout << MyAdd()(3, 4) << endl;
}

int main() {
	test();
	system("pause");
	return 0;
}
7
7
请按任意键继续. . .

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: C++允许重载任何一个关系运算符,包括 <、>、<=、>=、==等。重载后的关系运算符可以用于比较类的对象,也适用于许多C++内置的数据类型。\[1\]运算符重载的语法是通过定义函数实现的,这样可以大大缩减代码长度。\[2\]为什么要重载运算符呢?对于操作系统基本的数据类型,编译器知道如何进行运算,但是对于自定义的数据类型,比如结构体或类,编译器就不知道如何对其进行运算了。这时候就需要重载相应的运算符来定义自定义类型的运算行为。\[3\]运算符重载的规则包括:重载的函数必须是类的成员函数或友元函数,不能改变运算符的优先级和结合性,不能改变运算符的操作数个数,不能改变运算符的原有语义等。具体的示例可以参考C++的文档或教程。 #### 引用[.reference_title] - *1* [十个 C++ 运算符重载示例,看完不懂打我...](https://blog.csdn.net/luckydarcy/article/details/121599696)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [c++ 运算符重载](https://blog.csdn.net/weixin_54891898/article/details/120495677)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [c++运算符重载详解及代码示例](https://blog.csdn.net/weixin_46935110/article/details/127294153)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值