在C++中使用运算符重载比较哪个字符串更大

Compare which string is greater using Operator overloading in C++

本文关键字:字符串 比较 重载 C++ 运算符      更新时间:2023-10-16

我正在尝试使用运算符重载进行字符串比较,我正在使用>运算符,我没有得到正确的输出,你能告诉我我在这里犯的错误是我的代码吗

#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
class strclass
{
 public:
 char s1[20];
void getdata()
 {
	cin>>s1;
 }
void showdata()
 {
	cout<<s1;
 }
  int  operator>(strclass obj)
  {
   int temp,temp1;
   temp=strlen(s1);
   temp1=strlen(obj.s1);
   if(temp>temp1)
   {
    return 1;
   }
   else
   return 0;
  }
};
void main()
{
clrscr();
  strclass obj1,obj2;
  int temp3;
  if(obj1>obj2)
  {
   cout<<"string 1 is greater";
  }
  else
  {
   cout<<"string 2 is greater";
  }
  cout<<"enter string 1"<<endl;
  obj1.getdata();
 // obj1.showdata();
  cout<<"enter string 2"<<endl;
   obj2.getdata();
//   obj2.showdata();
   getch();
}

我正在使用基本的库函数。谢谢

  1. 在比较字符串之前,您需要先放入数据
  2. 运算符应返回一个int
  3. 对于具有公共s1成员的类,应该为bool operator<(strclass s1, strclass s2)形式的比较运算符使用一个自由函数,而不是成员函数,这样可以增加封装性