C++单目运算符的重载与双目运算符的重载【案例】

一、单目运算符的重载

#include <iostream>
using namespace std;
class Time
{
public:
	Time()  //定义无参构造函数 
	{
		minute=0; sec=0;
	}
	Time(int m, int s):minute(m), sec(s){  }  //初始化列表方法定义带参构造函数 
	Time operator ++ ();  //声明运算符重载成员函数
	void display()
	{
		cout << minute << ":" << sec << "     ";  //定义时间输出函数 
	}
private:  //私有成员数据
	int minute;
	int sec; 
};

//定义运算符重载成员函数 
Time Time::operator ++() 
{
	if(++sec>=60)
	{
		sec -= 60;  //将秒置零 
		++minute;  //满60秒将分钟加1 
		return *this;  //返回当前对象的值 
	}
}

int main()
{
	Time time1(34,0);  //实例化对象time1
	for(int i=0; i<61; i++)
	{
		++time1;  //循环61次,每次将时间加1操作 
		time1.display();  //调用对象的输出函数 
	}
	return 0; 
}

1-1

二、双目运算符的重载,使其能运算字符串的> < ==

#include <iostream>
#include <string.h>  //引入字符串库 
using namespace std;

class String
{
public:
	String()   //定义默认构造函数
	{
		p=NULL; 
	} 
	String(char *str);  //声明带参构造函数
	//声明重载运算符>的函数,类型为bool类型,参数为两个引用类型,即对象string1,string2
	//声明运算符函数为友元函数 
	friend bool operator > (String &string1, String &string2);
	void display();  //定义普通成员函数,显示出数据
private:
	char *p;   //定义字符型指针,用于指向字符串 
};

//定义带参构造函数 
String::String(char *str)
{
	p= str;  //使p指针指向实参字符串 
}

//输出p所指向的字符串
void String::display()
{
	cout << p;
}

//定义双目>号运算符重载函数 
bool operator > (String &string1, String &string2)
{
	if(strcmp(string1.p, string2.p)>0)  //调用string库 字符串比较函数
		return true;
	else return false; 
}

int main()
{
	String string1("Hello"), string2("Book");  //实例化两个对象
	string1.display();  //调用共有成员函数 
	cout << endl;
	string2.display();
	bool res;  //存放字符串的判断大小的返回值 
	string result;  //存放是大于还是小于 
	
	cout << endl;
	res= string1>string2;
	if(res==1)  //若重载函数<的返回值为1,则表明string1大于string2 
		result= "大于"; 
	else
		result= "小于";
	cout << "字符串";
	string1.display();
	cout << result;   //判断结果 
	string2.display();
	cout << endl;
		 
	return 0;	 
}

2-1
2-2
2-3

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸿蒙Next

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值