&& || 不能进行运算符重载,因为运算符重载不能进行截断操作
截断操作就是当 a || b,a为真的时候就不会再判断b了,但是运算符重载不能达到这效果。
类定义
// 类定义
#include <iostream>
using namespace std;
//c中没有字符串 字符串类(c风格的字符串)
//空串 ""
class MyString
{
friend ostream& operator<<(ostream &out, MyString &s);
friend istream& operator>>(istream &in, MyString &s);
public:
MyString(int len = 0);
MyString(const char *p);
MyString(const MyString& s);
~MyString();
public: //重载=号操作符
MyString& operator=(const char *p);
MyString& operator=(const MyString &s);
char& operator[] (int index);
public: //重载 == !==
bool operator==(const char *p) const;
bool operator==(const MyString& s) const;
bool operator!=(const char *p) const;
bool operator!=(const MyString& s) const;
public:
int operator<(const char *p);
int operator>(const char *p);
int operator<(const MyString& s);
int operator>(const MyString& s);
//把类的指针 露出来
public:
char *c_str()
{
return m_p;
}
const char *c_str2()
{
return m_p;
}
int length()
{
return m_len;
}
private:
int m_len;
char *m_p;
};
<< 和 >>
操作符重载
ostream& operator<<(ostream &out, MyString &s)
{
out<<s.m_p;
return out;
}
istream& operator>>(istream &in, MyString &s)
{
cin>>s.m_p;
return in;
}
copy
构造函数
//拷贝构造函数
//MyString s3 = s2;
MyString::MyString(const MyString& s)
{
this->m_len = s.m_len;
this->m_p = new char[m_len +1];
strcpy(this->m_p, s.m_p);
}
=
运算符重载
//// s4 = "s2222";
MyString& MyString::operator=(const char *p)
{
//1 旧内存释放掉
if (m_p != NULL)
{
delete [] m_p;
m_len = 0;
}
//2 根据p分配内存
if (p == NULL)
{
m_len = 0;
m_p = new char[m_len + 1];
strcpy(m_p, "");
}
else
{
m_len = strlen(p);
m_p = new char[m_len + 1];
strcpy(m_p, p);
}
return *this;
}
// s4 = s2;
MyString& MyString::operator=(const MyString &s)
{
//1 旧内存释放掉
if (m_p != NULL)
{
delete [] m_p;
m_len = 0;
}
//2 根据s分配内存
m_len = s.m_len;
m_p = new char[m_len + 1];
strcpy(m_p, s.m_p);
return *this;
}
[]
运算符重载
char& MyString::operator[](int index)
{
return m_p[index];
}
== 和 !=
运算符重载
//if (s2 == "s222222")
bool MyString::operator==(const char *p) const
{
if (p == NULL)
{
if (m_len == 0)
{
return true;
}
else
{
return false;
}
}
else
{
if (m_len == strlen(p))
{
return !strcmp(m_p, p);
}
else
{
return false;
}
}
}
bool MyString::operator!=(const char *p) const
{
return !(*this == p);
}
bool MyString::operator==(const MyString& s) const
{
if (m_len != s.m_len)
{
return false;
}
return !strcmp(m_p, s.m_p);
}
bool MyString::operator!=(const MyString& s) const
{
return !(*this == s);
}
> 和<
操作符重载
//if (s3 < "bbbb")
int MyString::operator<(const char *p)
{
return strcmp(this->m_p , p);
}
int MyString::operator>(const char *p)
{
return strcmp(p, this->m_p);
}
int MyString::operator<(const MyString& s)
{
return strcmp(this->m_p , s.m_p);
}
int MyString::operator>(const MyString& s)
{
return strcmp(s.m_p, m_p);
}