运算符重载(c++)

本文详细介绍了C++中的运算符重载,包括加法、左移、递增、赋值和关系运算符的重载,并通过实例展示了如何实现。此外,还探讨了函数调用的重载,即仿函数的概念,以及其在实际编程中的应用。这些内容有助于理解C++中如何自定义操作以适应不同数据类型和需求。

运算符重载:
概念:对已有的运算符重新进行定义,赋予另外一种功能,以适应不同的数据类型
1.加法运算符的重载:实现对两个数据类型相加的运算

#include<iostream>
using namespace std;
class Person
{
public:
	/*
	//成员运算符重载
	Person operator+ (Person& p)
	{
		Person tmp;
		tmp.m_a = this->m_a + p.m_a;
		tmp.m_b = this->m_b + p.m_b;
		return tmp;
	}
	*/
	int m_a;
	int m_b;
};
//全局函数 运算符重载 加号
Person operator+ (Person& p1, Person& p2)
{
	Person tmp;
	tmp.m_a = p1.m_a + p2.m_a;
	tmp.m_b = p1.m_b + p2.m_b;
	return tmp;
}
//函数重载 例如 Person P4 = P1+10
Person operator+ (Person& p1, int num)
{
	Person tmp;
	tmp.m_a = p1.m_a + num;
	tmp.m_b = p1.m_b + num;
	return tmp;
}
void test01()
{
	Person p1;
	p1.m_a = 10;
	p1.m_b = 10;
	Person p2;
	p2.m_a = 10;
	p2.m_b = 10;
	//成员函数的本质调用 Person p3 = p1.operator+(p2) 简化为
	Person p3 = p1 + p2;
	cout << "p3 m_a的值:" << p3.m_a << endl;
	cout << "p3 m_b的值:" << p3.m_b << endl;
	//全局函数调用的本质 Person operator + (p1,p2)
	//函数的重载 例如 
	Person p4 = p1 + 10;
}


int main()
{
	test01();
	return 0;
}

2.左移运算符的重载:可以输出自定义的数据类型“<<”

#include<iostream>
using namespace std;

class Person
{//不能利用成员函数重载 因为无法实现 cout在左侧 void operator (cout)
	friend ostream& operator<< (ostream& cout, Person p);//作为友元 可以访问persom的私有属性
public:
	Person(int a, int b)
	{
		this->m_a = a;
		this->m_b = b;
	}

private:
	int m_a;
	int m_b;
};
//只能利用全局函数进行重载
//void  operator<< ( ostream &cout, Person &p)//本质 operator<<(cout,p) 简化为cout<<p
//{
//	cout << "m_a = :" << p.m_a <<" m_b= :" << p.m_b << endl;
//
//}				ostream 数据输出流类型 (cout)

ostream &operator<< (ostream& cout, Person p)//本质 operator<<(cout,p) 简化为cout<<p
{
	cout << "m_a = :" << p.m_a << " m_b= :" << p.m_b << endl;
	return cout; //此时可以在cout<<p 后面无限追加东西 例如 cout<<p<<endl
}
int main()
{	
	Person p(10,10);
	/*p.m_a = 10;
	p.m_b = 10;*/
	cout <<p<<"hello world"<< endl;
	return 0;
}

3.递增运算符的重载:

#include<iostream>
using namespace std;

//总结:前置递增返回引用,后置递增返回的是值
class MyInteger
{
	friend ostream& operator<< (ostream& cout, MyInteger myint);
public:
	MyInteger()
	{
		m_Num = 0;
	}
	//重载前置运算符 ++
	MyInteger & operator++()//这里的&是为了在同一块内存上进行操作
	{
		m_Num++;
		return *this;//链式编程
	} 
	//重载后置运算符
	MyInteger operator++(int)//int是占位参数 与上一个相区别 
	{
		//先记录保存当前的置再递增
		MyInteger tmp = *this;
		m_Num++;
		return tmp;
	}

private:
	int m_Num;
};

ostream &operator<< (ostream &cout, MyInteger myint)
{
	cout << myint.m_Num;
	return cout;

}
void test01()
{
	MyInteger myint;
	cout << ++(++myint) << endl;

}
void test02()
{

	MyInteger myint;
	cout << (myint ++)<< endl; //在后置加加的过程没有 (myint++)++这种操作
	cout << myint << endl;
}

int main()
{
	test02();
	return 0;
}

4.赋值运算符的重载:

/*
c++编译器至少给一个类添加了四个函数
1.默认构造函数(无参,函数体为空)
2。默认析构函数(无参,函数体为空)
3.默认拷贝构造函数,对属性进行值拷贝
4.赋值运算符operator= ,对属性进行值拷贝

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

#include<iostream>
using namespace std;
class Person
{
public:
	Person(int age)
	{
		m_age = new int(age);//堆区开辟一个区域并且用m_age来进行维护
	}							//程序员开辟堆区的空间 得自己手动释放

	
	~Person()//析构函数
	{
		if (m_age != NULL)
		{
			delete m_age;
			m_age = NULL;
			//delete释放的是指针所指向的空间,不是指针的值,
			//指针的值就是它所指向的那片空间的地址,所以delete之后,还有将指针的值置为NULL
		}
	}
	Person& operator=(Person& p)
	{
		//编译器默认的是浅拷贝
		 //m_age = p.m_age

		//应该先判断是否有属性在堆区,有的话先把他释放干净,然后再深拷贝
		if (m_age != NULL)
		{
			delete m_age;
			m_age = NULL;
		}
		m_age = new int(*p.m_age);
		return *this;
	}
	int* m_age;
};

void test01()
{
	Person p1(18);
	Person p2(28);

	cout << "P1的年龄为:" << *p1.m_age << endl;
	cout << "P2的年龄为:" << *p2.m_age << endl;
}
void test02()
{
	Person p1(18);
	Person p2(28);
	Person p3(38);

	p3 = p2 = p1;
	cout << "P1的年龄为:" << *p1.m_age << endl;
	cout << "P2的年龄为:" << *p2.m_age << endl;
	cout << "P3的年龄为:" << *p2.m_age << endl;
}
int main()
{
	test02();
	return 0; 
}

5.关系运算符的重载:

//可以让两个自定义类型的数据类型进行对你操作
#include<iostream>
#include<string>
using namespace std;
class Person
{public:

	Person (string name ,int age)
	{
		this->m_name = name;
		this->m_age = age;
	}

	bool operator==(Person& p)
	{
		if (this->m_age == p.m_age && this->m_name == p.m_name)
		{
			return true;

		}return false;
	}
	string m_name;
	int m_age;
};
void test()
{
	Person p1("李四",18);
	Person p2("李四",18);
	if (p1==p2)
	{
		cout << "p1 = p2" << endl;
	}
	else
	{
		cout << "p1 != p2" << endl;
	}
}
int main()
{
	test();
	return 0;
}

6.函数调用重载;

/*
1.函数运用运算符()也可以重载
2.由于重载后使用的方式非常像函数的调用,因此称为仿函数
3.仿函数没有固定写法,非常灵活
*/

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


class Print
{ //重载函数调用运算符
public:
	void operator()(string test)
	{
		cout << test << endl;
	}

};

void test2(string test)
{

	cout << test << endl;
}
void test()
{
	Print p;
	p("hello world"); //原本是用函数来实现的,由于使用起来非常像函数的调用,也称仿函数
	test2("hello world02");//使用函数test2()来实现
}
/*仿函数非常灵活,没有固定的写法*/
//例如加法类
class Add
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};
void test3()
{
	Add add;
	int ret = add(2, 3);
	cout <<"ret:"<< ret << endl;
	//匿名函数函数对象(当前行执行立即释放)
	cout << Add()(100, 100) << endl;
}
int main()
{
	test();
	test3();
	return 0;
}/*
1.函数运用运算符()也可以重载
2.由于重载后使用的方式非常像函数的调用,因此称为仿函数
3.仿函数没有固定写法,非常灵活
*/

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


class Print
{ //重载函数调用运算符
public:
	void operator()(string test)
	{
		cout << test << endl;
	}

};

void test2(string test)
{

	cout << test << endl;
}
void test()
{
	Print p;
	p("hello world"); //原本是用函数来实现的,由于使用起来非常像函数的调用,也称仿函数
	test2("hello world02");//使用函数test2()来实现
}
/*仿函数非常灵活,没有固定的写法*/
//例如加法类
class Add
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};
void test3()
{
	Add add;
	int ret = add(2, 3);
	cout <<"ret:"<< ret << endl;
	//匿名函数函数对象(当前行执行立即释放)
	cout << Add()(100, 100) << endl;
}
int main()
{
	test();
	test3();
	return 0;
}

### C++ 时间类 运算符重载 实现方法 在 C++ 中,可以通过运算符重载技术为自定义的时间类提供类似于内置数据类型的操作方式。以下是关于如何实现时间类中的运算符重载的具体说明。 #### 1. **前置++ 和 后置++ 的重载** 对于时间类 `Time`,可以重载前置和后置的自增运算符(即 `++`)。者的主要区别在于返回值的不同: - 前置++ 返回的是修改后的对象本身。 - 后置++ 需要先保存当前状态的对象副本,在完成自增后再返回这个副本。 下面是具体的实现代码: ```cpp class Time { private: int _hour; int _min; int _sec; public: Time(int hour = 0, int min = 0, int sec = 0) : _hour(hour), _min(min), _sec(sec) {} // 打印时间的方法 void Print() const { std::cout << _hour << ":" << _min << ":" << _sec << std::endl; } // 前置++ Time& operator++() { // ++a Increment(); return *this; // 返回当前对象的引用 } // 后置++ Time operator++(int) { // a++ Time temp(*this); // 创建临时变量存储原始值 Increment(); // 修改原对象 return temp; // 返回未修改前的状态 } private: void Increment() { _sec++; if (_sec >= 60) { _sec -= 60; _min++; } if (_min >= 60) { _min -= 60; _hour++; } if (_hour >= 24) { _hour -= 24; } } }; int main() { Time t(23, 59, 58); (++t).Print(); // 输出: 23:59:59 (前置++) t++.Print(); // 输出: 23:59:59 (后置++) t.Print(); // 输出: 0:0:0 (实际已更新) return 0; } ``` 以上代码展示了如何通过私有成员函数 `_Increment()` 来统一处理秒数溢出逻辑[^1]。这样不仅提高了代码可读性,还减少了重复代码。 --- #### 2. **加法运算符 (+)** 为了支持个时间对象相加的操作,可以重载二元加法运算符 (`+`)。其基本思路是将个时间对象的小时、分钟和秒分别累加,并考虑进位情况。 ```cpp // 加法运算符重载 Time operator+(const Time& other) const { int totalSecs = this->_sec + other._sec; int totalMins = this->_min + other._min + (totalSecs / 60); int totalHours = this->_hour + other._hour + (totalMins / 60); totalSecs %= 60; totalMins %= 60; totalHours %= 24; return Time(totalHours, totalMins, totalSecs); } // 测试代码 int main() { Time t1(10, 30, 45); Time t2(13, 29, 15); Time result = t1 + t2; // 调用operator+ result.Print(); // 输出: 24:0:0 或者简化为 0:0:0 return 0; } ``` 此部分实现了段时间相加的功能,并自动调整超出范围的部分[^4]。 --- #### 3. **赋值运算符 (=) 的重载** 当创建一个新对象并将其初始化为另一个已有对象时,默认情况下会调用拷贝构造函数;但如果希望显式控制这一过程,则需要重载赋值运算符。通常还需要注意自我赋值的情况以避免潜在错误。 ```cpp // 拷贝赋值运算符重载 Time& operator=(const Time& other) { if (this != &other) { // 防止自我赋值 _hour = other._hour; _min = other._min; _sec = other._sec; } return *this; } ``` 这段代码确保了即使发生自我赋值也不会引发问题[^2]。 --- #### 4. **其他可能的扩展功能** 除了上述提到的内容外,还可以进一步探索更多实用场景下的运算符重载,比如: - 减法运算符 (-),用于计算个时间之间的差值; - 输入/输出流运算符 (<< 和 >>),便于直接打印或输入时间对象的数据; - 关系运算符 (<、>、== 等),用来比较不同时间段的关系。 这些都可以基于具体需求逐步完善。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值