在程序笔试面试过程中String类的是实现是经常被问到的,为了便于记忆,现在整理一下。
1 #ifndef STRING_H_
2 #define STRING_H_
3 #include <stdio.h>
4 #include <iostream>
5 using namespace std;
6 class String
7 {
8 friend ostream &operator<<(ostream &,const String &);
9 friend istream &operator>>(istream &,String &);
10 public:
11 String(const char* str=NULL);
12 String(const String &other);
13 ~String(void);
14 const String &operator = (const String &other);
15 private:
16 char *m_data;
17 };
18 #endif
19
1 #include "String.h"
2 #include <string.h>
3 #include <stdio.h>
4 using namespace std;
5 String::String(const char *str)
6 {
7 cout<<"constructor function is called.\n";
8 if(NULL==str)
9 {
10 m_data=new char[1];
11 *m_data='/0';
12 }
13 else
14 {
15 int length=strlen(str);
16 m_data=new char[length+1];
17 strcpy(m_data,str);
18 }
19 }
20 String::~String(void)
21 {
22 cout<<"destructor function is called.\n";
23 delete [] m_data;
24 }
25 String::String(const String &other)
26 {
27 cout<<"copy constructor function is called.\n";
28 int length=strlen(other.m_data);
29 m_data=new char[length+1];
30 strcpy(m_data,other.m_data);
31 }
32 const String& String::operator=(const String& other)
33 {
34 cout<<"assign function is called.\n";
35 if(this==&other)
36 return *this;
37 delete[] m_data;
38 int length=strlen(other.m_data);
39 m_data=new char[length+1];
40 strcpy(m_data,other.m_data);
41 return *this;
42 }
43 ostream &operator<<(ostream &output,const String &s)
44 {
45 output<<s.m_data;
46 return output;
47 }
48 istream &operator>>(istream &input,String &s)
49 {
50 char temp[100];
51 input>>temp;
52 s=temp;
53 return input;
54 }
1 #include <String.h>
2 #include <iostream>
3 using namespace std;
4 int main()
5 {
6 String s="hello";
7 cout<<s<<endl;
8 String i;
9 cin>>i;
10 cout<<i<<endl;
11 return 0;
12 }
13
输入和输出操作符不能声明为类的成员函数,必须为普通函数,并且为类的友元函数,因为他们都要访问类的成员函数,输入输出操作符的左操作数是IO流对象的引用,右操作数才是类的对象,因此不能为类的成员函数(类的成员函数隐含的第一个操作数,是指向该类或该类派生类对象的this指针)。
在这里重载了有一个参数的构造函数,此时系统将不会提供不带参数的构造函数。
在构造函数中使用了深拷贝,在某些状况下,类内成员变量需要动态开辟堆内存,如果实行位拷贝,也就是把对象里的值完全复制给另一个对象,如A=B。这时,如果B中有一个成员变量指针已经申请了内存,那A中的那个成员变量也指向同一块内存。这就出现了问题:当B把内存释放了(如:析构),这时A内的指针就是野指针了,出现运行错误。
深拷贝和浅拷贝可以简单理解为:如果一个类拥有资源,当这个类的对象发生复制过程的时候,资源重新分配,这个过程就是深拷贝,反之,没有重新分配资源,就是浅拷贝。