重载双目运算符

简介: 重载双目运算符


/*
代码功能:重载双目运算符
作者:令狐荣豪
时间:2019/6/29
*/
#include<iostream>
using namespace std;
class String
{
public:
  String() //定义默认构造函数
  { 
    p = NULL; 
  }
  String(char *str);//声明构造函数
  friend bool operator>(String &string1, String &string2);//声明重载函数为友元函数
  /*====================扩展==============================*/
  friend bool operator <(String &string1, String &string2);
  friend bool operator==(String &string1, String &string2);
  /*======================================================*/
  void display();
  void compare();
private:
  char *p;
};
String::String(char *str)//定义构造函数
{
  p = str;//使p指向实参字符串
}
void String::display()//输出p指向的字符串
{
  cout << p;
}
/*定义重载运算符函数*/
/*----------------------------------------------*/
bool operator >(String &string1, String &string2)
{
  if (strcmp(string1.p, string2.p) > 0)
    return true;
  else
    return false;
}
/*----------------------------------------------*/
bool operator <(String &string1, String &string2)
{
  if (strcmp(string1.p, string2.p) < 0)
    return true;
  else
    return false;
}
/*----------------------------------------------*/
bool operator ==(String &string1, String &string2)
{
  if (strcmp(string1.p, string2.p) == 0)
    return true;
  else
    return false;
}
/*-----------------------------------------------*/
void compare(String &string1, String &string2)
{
  if (operator>(string1, string2) == 1)
  {
    string1.display(); 
    cout << ">";
    string2.display();
    cout << endl;
  }
  if (operator<(string1, string2) == 1)
  {
    string1.display();
    cout << "<";
    string2.display();
    cout << endl;
  }
  if (operator==(string1, string2) == 1)
  {
    string1.display();
    cout << "==";
    string2.display();
    cout << endl;
  }
}
int main()
{
  String string1("Hello"), string2("Book"),string3("Computer"),string4("Hello");//定义对象
  compare(string1, string2);
  compare(string2, string3);
  compare(string1, string4);
  return 0;
}


目录
相关文章
|
5月前
|
Java
方法的重载
方法的重载
41 1
|
5月前
|
编译器 C#
C#重载详解
C#重载详解
40 0
|
5月前
|
算法 安全 编译器
【C++运算符重载】深入理解C++中的类型转换与重载
【C++运算符重载】深入理解C++中的类型转换与重载
77 0
|
5月前
|
C++
44重载双目运算符
44重载双目运算符
33 0
C++重载、重写、重定义
C++重载、重写、重定义
84 0
|
11月前
|
C++
39 C++ - 为什么不能重载&&、||
39 C++ - 为什么不能重载&&、||
34 0
|
11月前
|
C++
54 C++ - 重写 重载 重定义
54 C++ - 重写 重载 重定义
29 0
4.【拷贝构造函数与重载】
4.【拷贝构造函数与重载】
34 1
函数的重载
函数的重载
27 0