#include<iostream>
#include<cstring>
using namespace std;
class mystring
{
public:
mystring()
{
m_p = new char[10];
cout<<"无参构造被调用"<<endl;
m_len = 0;
}
mystring(const char *str)
{
m_len = strlen(str);
m_p = new char[m_len+1];
strcpy(m_p,str);
//cout<<m_p<<endl;
}
mystring(const mystring &str)
{
m_len = strlen(str.m_p );
m_p = new char[m_len+1];
strcpy(m_p,str.m_p);
cout<<"拷贝构造被调用"<<endl;
}
void print()
{
cout<<"m_p:"<<m_p<<endl;
}
~mystring()
{
delete m_p;
cout<<"调用析构函数"<<endl;
}
void apd();
mystring append(mystring p);
void at(int num);
mystring insert(int num,mystring s);
mystring remove(int a,int b);
char operator[](int n)
{
cout<<"重载[]"<<endl;
return *(m_p + n);
}
mystring operator=(mystring a);
mystring operator+=(mystring &s);
mystring operator-=(mystring &s);
friend istream &operator>>(istream &in, mystring &s);
friend ostream &operator<<(ostream &out, mystring &s);
private:
char *m_p;
int m_len;
};
mystring mystring::append(mystring p)
{
strcat(this->m_p,p.m_p);
cout<<"append:"<<m_p<<endl;
return *this;
}
void mystring::at(int num)
{
for (int i = 0; i < strlen(m_p); i++)
{
if (num == i)
{
cout<<"at(3):"<<m_p[i]<<endl;
return;
}
}
}
mystring mystring::insert(int num,mystring s)
{
mystring s1;
strncpy(s1.m_p, m_p, num);
strcat(s1.m_p, s.m_p);
int n = strlen(s1.m_p);
if(num != strlen(m_p))
{
for(int i = num; i < strlen(m_p); i++)
{
s1.m_p[n] = m_p[i];
n++;
}
}
s1.m_p[n] = '\0';
strcpy(m_p,s1.m_p);
cout<<"insert:"<<m_p<<endl;
return *this;
}
mystring mystring::remove(int i,int j)
{
int n = j - i;
for(i ,j ;i < (strlen(m_p) - n);i++,j++)
{
m_p[i] = m_p[j];
}
m_p[strlen(m_p)-n] = '\0';
cout<<"move:"<<m_p<<endl;
return *this;
}
mystring mystring::operator=(mystring a)
{
cout << "= 重载" << endl;
strcpy(m_p,a.m_p);
return *this;
}
mystring mystring::operator+=(mystring &s)
{
cout << "+= 重载" << endl;
strcat(this->m_p ,s.m_p);
return *this;
}
mystring mystring::operator-=(mystring &s)
{
cout << "-= 重载" << endl;
mystring temp;
int n = strlen(s.m_p);
int m = strlen(m_p);
if (strlen(m_p) >= strlen(s.m_p))
{
strncpy(temp.m_p, m_p, m - n);
temp.m_p[m - n] = '\0';
strcpy(m_p, temp.m_p);
}
else
{
strncpy(temp.m_p, s.m_p, n - m);
temp.m_p[n - m] = '\0';
strcpy(m_p, temp.m_p);
}
return *this;
}
istream &operator>>(istream &in, mystring &s)
{
cout << ">>重载" << endl;
in >> s.m_p;
s.m_len = strlen(s.m_p);
return in;
}
ostream &operator<<(ostream &out, mystring &s)
{
cout << "<<重载" << endl;
out << s.m_p<<endl;;
return out;
}
int main()
{
mystring m("hello");
mystring m1("word");
m.append("word");
m.at(3);
m.insert(2,"123");
m.remove(2,9);
mystring str;
mystring str1("word");
str = "hello";
str.print();
str += str1;
str.print();
str -= str1;
str.print();
cin>>str;
cout<<str;
return 0;
}
c++用类封装一个mystring,动态数组,构造函数,析构函数,拷贝函数,append()等函数应用
最新推荐文章于 2024-05-31 14:42:05 发布