计划字符串类 运算符重载 C++实现 QT情况

打印 上一主题 下一主题

主题 1004|帖子 1004|积分 3012

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
标题:计划字符串类, 支持下面的操作
MyString  s1; // 默认构造函数
MyString s2("hello"); // 含参构造函数
MyString  s3(s1); // 传参构造函数
MyString  s4(5, 'c'); // 自定义构造函数
= // 运算符重载
==    !=   >   <  // 运算符重载

代码:
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. class Mystring{
  5.     // <<
  6.     friend ostream& operator<<(ostream &out,Mystring &s);
  7.     // >>
  8.     friend istream& operator>>(istream &in,Mystring &s);
  9. private:
  10.     char *m_space; // 存储数据
  11.     size_t m_len; // 字符串长度
  12. public:
  13.     // 默认构造函数
  14.     Mystring(){
  15.         m_space = new char;
  16.         strcpy(m_space,"");
  17.         m_len = 0;
  18.     }
  19.     // 构造函数
  20.     Mystring(const char *indata){
  21.         m_len = strlen(indata);
  22.         m_space = new char[m_len + 1];
  23.         strcpy(m_space,indata);
  24.     }
  25.     // 拷贝构造函数(深拷贝)
  26.     Mystring(const Mystring &s){
  27.         m_len = s.m_len;
  28.         m_space = new char[m_len + 1];
  29.         strcpy(m_space,s.m_space);
  30.     }
  31.     // 析构函数
  32.     ~Mystring(){
  33.         if(m_space != nullptr){
  34.             delete [] m_space;
  35.             m_space = nullptr;
  36.         }
  37.     }
  38.     // 重载赋值运算符 =
  39.     Mystring& operator=(const Mystring &s){
  40.         if(m_space != nullptr){
  41.             delete [] m_space;
  42.             m_space = nullptr;
  43.         }
  44.         m_len = s.m_len;
  45.         m_space = new char[m_len + 1];
  46.         strcpy(m_space,s.m_space);
  47.         return *this;
  48.     }
  49. };
  50. // <<
  51. ostream& operator<<(ostream &out,Mystring &s){
  52.     out<<s.m_space;
  53.     return  out;
  54. }
  55. istream& operator>>(istream &in,Mystring &s){
  56.     // 对之前的内存进行管理(避免内存泄漏)
  57.     if(s.m_space != nullptr){
  58.         delete [] s.m_space;
  59.         s.m_space = nullptr;
  60.     }
  61.     // 输入新的字符串
  62.     char buf[1024];
  63.     in>>buf;
  64.     s.m_len = strlen(buf);
  65.     s.m_space = new char[s.m_len + 1];
  66.     strcpy(s.m_space,buf);
  67.     return  in;
  68. }
  69. int main(){
  70.     Mystring s1;
  71.     Mystring s2("Hello");
  72.     cout<<"Please input data:"<<endl;
  73.     cin>>s2;
  74.     s1 = s2;
  75.     cout<<"s2: "<<s2<<endl;
  76.     cout<<"s1: "<<s1<<endl;
  77.     return 0;
  78. }
复制代码
输出:


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

万有斥力

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表