Friday, May 13, 2016

Bài tập chồng toán tử +,> trong xâu bằng C++


//Họ Tên: Trần Văn Linh
//MaSV:581597
//Lớp:K58QLTT

----------------------------------------------------------------------------------------------------------------------------------

#include<iostream>
#include<string.h>
#include<stdio.h>

using namespace std;

//Khai bao lop
class xau
{
private:
 enum {size=256};
         char str[size];
public:
 xau();
 xau(const char *s);
 xau operator+(xau &s2); //hàm cộng hai xâu
 int operator>(xau &s2);//hàm so sánh > hai xâu
          friend istream& operator>>(istream& cin,xau &s2); //Nhập xâu
 friend ostream& operator<<(ostream& cout,xau &s2);//In xâu
};
//==Chuong trinh chinh==
int main()
{
xau s1("Day la xau 1 ");
xau s2,s3("Day la xau 2 ");

s2=s1+s3;

cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;

s1>s3?cout<<s1:cout<<s3;

return 0;
}
//===Dinh nghia ham===
xau::xau()
{
           strcpy(str,"");
}
//-------------
xau::xau(const char *s)
{
strcpy(str,s);
}
//-------------
xau xau::operator+(xau &s2)
{
xau tong;
strcpy(tong.str,str);
if(strlen(str)+strlen(s2.str)<size)
strcat(tong.str,s2.str);
else
cout<<"Xau qua dai khong the noi duoc.!";
return tong;
}
//-------------
int xau::operator>(xau &s2)
{
return (strcasecmp(str,s2.str)>0);
}
//-------------
istream& operator>>(istream& cin, xau &s2)
{
          cout<<"Nhap xau:";
 scanf(" ");//Khu dau enter
 cin.get(s2.str,sizeof(s2.str));
 return cin;
}
//-------------
ostream& operator<<(ostream& cout,xau &s2)
{
cout<<s2.str;
return cout;
}
//-------------

0 comments:

Post a Comment