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

2023-05-16

文章目录

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

一、单目运算符的重载

#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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐