中易网

用C++写一个类的程序

答案:3  悬赏:0  
解决时间 2021-04-27 03:33
  • 提问者网友:wodetian
  • 2021-04-27 00:44

要求这个类包括

1.Write your first class named mystring

 

2.Constructor,destructor(at least three constructer)

 

3.Deep copy

 

4.Integrate your previous functions such as upper(),lower() into this class.

 


 

最佳答案
  • 二级知识专家网友:晨与橙与城
  • 2021-04-27 02:07
#include <iostream>
#include <cstring>
using namespace std;
class mystring {
public:
    mystring() { construct_from(""); }
    mystring(const char* str) { construct_from(str); }
    mystring(const mystring& m) { construct_from(m.s); }
    mystring& operator = (const mystring& rhs)
    {
    if(&rhs == this || strcmp(s, rhs.s) == 0)
    return *this;
    construct_from(rhs.s);
    return *this;
    }
    friend ostream& operator << (ostream& os, const mystring& m)
    {
    return os << m.s;
    }
    ~mystring() { delete [] s; }
private:
    void construct_from(const char* str)
    {
    len = strlen(str);
    s = new char[len+1];
    memcpy(s, str, len);
    }
   
    char* s;
    size_t len;
};
int main()
{
    mystring a, b("123"), c(b);
    cout << b << ' ' << c << endl;
    a = b;
    cout << a << endl;
    a = "456";
    cout << a << endl;
}
全部回答
  • 1楼网友:旧事诱惑
  • 2021-04-27 03:14
这个没有什么的了吧
  • 2楼网友:转身→时光静好
  • 2021-04-27 02:36

#include<iostream> using namespace std;

class mystring;//declaration of mystring

ostream &operator<<(ostream &out,const mystring &s);// declaration of function operator<<

class mystring { public:  mystring()//constructor function 1  {   m_pstr=NULL;  }  mystring(const char *p)//constructor function 2  {   m_pstr=new char[strlen(p)+1];   strcpy(m_pstr,p);  }  mystring(const mystring &s)//constructor function 3<===>deep copy  {   m_pstr=new char[strlen(s.m_pstr)+1];   strcpy(m_pstr,s.m_pstr);  }  mystring &operator=(const mystring &s)//overload operator=  {   delete []m_pstr;   m_pstr=new char[strlen(s.m_pstr)+1];   strcpy(m_pstr,s.m_pstr);   return *this;  }  mystring &operator+=(const mystring &s)//overload operator+=  {   char *pTemp=new char[strlen(m_pstr)+1];   strcpy(pTemp,m_pstr);   delete []m_pstr;   m_pstr=new char[strlen(pTemp)+strlen(s.m_pstr)+1];   strcpy(m_pstr,pTemp);   strcat(m_pstr,s.m_pstr);   return *this;  }  mystring operator+(const mystring &s)//overload operator+  {   mystring Test;   Test.m_pstr=new char[strlen(m_pstr)+strlen(s.m_pstr)+1];   strcpy(Test.m_pstr,m_pstr);   strcat(Test.m_pstr,s.m_pstr);   return Test;  }  friend ostream &operator<<(ostream &out,const mystring &s);//friend operator<<  ~mystring()//destructor function  {   delete []m_pstr;   m_pstr=NULL;  } private:  char *m_pstr; };

ostream &operator<<(ostream &out,const mystring &s) {  out<<s.m_pstr;  return out; }

int main() {  mystring Test1="Hello ";  mystring Test2="World!";  mystring Test3=Test1+Test2;  cout<<Test3<<endl;  return 0; }

That's all, if you need more functions,call me~

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息