服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数

详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数

2021-05-30 18:06爱思考的小鸟 C/C++

这篇文章主要介绍了详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数的相关资料,这里提供实例帮助大家理解掌握这部分内容,需要的朋友可以参考下

详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数

 编写类String 的构造函数、析构函数和赋值函数,已知类String 的原型为:

?
1
2
3
4
5
6
7
8
9
10
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operate =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
class String
{
public:
  String(const char *str=NULL);//普通构造函数
  String(const String &str);//拷贝构造函数
  String & operator =(const String &str);//赋值函数
  ~String();//析构函数
protected:
private:
  char* m_data;//用于保存字符串
};
 
//普通构造函数
String::String(const char *str)
{
  if (str==NULL)
  {
    m_data=new char[1]; //对空字符串自动申请存放结束标志'\0'的空间
    if (m_data==NULL)
    {//内存是否申请成功
     std::cout<<"申请内存失败!"<<std::endl;
     exit(1);
    }
    m_data[0]='\0';
  }
  else
  {
    int length=strlen(str);
    m_data=new char[length+1];
    if (m_data==NULL)
    {//内存是否申请成功
      std::cout<<"申请内存失败!"<<std::endl;
      exit(1);
    }
    strcpy(m_data,str);
  }
}
 
//拷贝构造函数
String::String(const String &other)
{ //输入参数为const型
  int length=strlen(other.m_data);
  m_data=new char[length+1];
  if (m_data==NULL)
  {//内存是否申请成功
    std::cout<<"申请内存失败!"<<std::endl;
    exit(1);
  }
  strcpy(m_data,other.m_data);
}
 
//赋值函数
String& String::operator =(const String &other)
{//输入参数为const型
  if (this == &other) //检查自赋值
  { return *this; }
 
  delete [] m_data;//释放原来的内存资源
 
  int length=strlen(other.m_data);  
  m_data= new char[length+1];
  if (m_data==NULL)
  {//内存是否申请成功
    std::cout<<"申请内存失败!"<<std::endl;
    exit(1);
  }
  strcpy(m_data,other.m_data);
 
  return *this;//返回本对象的引用
}
 
//析构函数
String::~String()
{
  delete [] m_data;
}
 
void main()
{
  String a;
  String b("abc");
  system("pause");
}

以上就是C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/chinawangfei/article/details/43372317

延伸 · 阅读

精彩推荐