【添加 -= 运算符重载】
#include <iostream>
#include <string>
using namespace std;
class string_ex : public string
{
public:
using string::replace; // 继承父类的全部replace重载函数
string_ex(const char *s);
void replace(const char *s1, const char *s2);
bool operator -= (const char *s);
};
string_ex::string_ex(const char *s) : string(s)
{
}
void string_ex::replace(const char *s1, const char *s2)
{
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
size_type pos = 0;
while ((pos = find(s1, pos)) != -1)
{
replace(pos, len1, s2);
pos += len2;
}
}
bool string_ex::operator -= (const char *s)
{
size_type len = length();
size_t slen = strlen(s);
if (len > slen)
{
size_t n = len - slen;
const char *p = data();
if (strcmp(p + n, s) == 0)
{
char *mem = new char[n];
memcpy(mem, p, n);
assign(mem, n);
delete[] mem;
return true;
}
}
return false;
}
int main(void)
{
string_ex str = "this is a string.";
if (str -= "string.")
cout << str << endl;
if (str -= "a")
cout << str << endl;
}