1、为什么重载函数里面的形参要用const修饰,有什么用?不加会影响什么?
2、重载输入运算符时,为什么要把str数组定义为static,如果没定义为static就会出现乱码,这是为什么?
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
public:
mystring() {} //无参构造函数
mystring(char s[]) :pstr(s), length(strlen(s)) {}//有参构造函数
//重载输入输出
friend istream& operator>>(istream& in, mystring& s);
friend ostream& operator<<(ostream& out, const mystring &s);
//重载+=
void operator+=(const mystring &s)
{
strcat(this->pstr, s.pstr);
this->length += strlen(s.pstr);
}
//重载=
void operator=(const mystring &s)
{
this->pstr = s.pstr;
this->length = strlen(s.pstr);
}
//重载==
int operator==(const mystring &s)
{
return strcmp(this->pstr, s.pstr) == 0;
}
//重载!=
int operator!=(const mystring &s)
{
return strcmp(this->pstr, s.pstr);
}
//重载>
int operator>(const mystring &s)
{
return strcmp(this->pstr, s.pstr) > 0;
}
//重载<
int operator<(const mystring &s)
{
return strcmp(this->pstr, s.pstr) < 0;
}
//重载下标运算符
char operator[](int n)
{
return *(this->pstr + n);
}
private:
char* pstr;
int length;
};
istream& operator>>(istream& in, mystring& s)
{
static char str[50];
cout << "请输入str数组的元素:";
in >> str;
s.pstr = str;
s.length = strlen(str);
return in;
}
ostream& operator<<(ostream& out,const mystring &s)
{
out << s.pstr;
return out;
}
int main()
{
char str[20];
mystring s1(str);
mystring s2;
cout << "请输入s2:" << endl;
cin >> s2;
cout << s2 << endl;
s2 += s1;
cout <<"s1+=s2后s2为:"<< s2 << endl;
s2 = s1;
cout << s2[3] << endl;
if (s1 != s2) {
cout << "s1!=s2" << endl;
}
if (s1 == s2) {
cout << "s1==s2" << endl;
}
if (s1 > s2) {
cout << "s1>s2" << endl;
}
if (s1 < s2) {
cout << "s1<s2" << endl;
}
return 0;
}