编程语言
首页 > 编程语言> > c++面试题string类的具体实现

c++面试题string类的具体实现

作者:互联网

 1 #include<iostream>
 2 //#include<ostream>
 3 //class ostream;
 4 class string
 5 {
 6 public:
 7     //constructor
 8     string(const char* str=nullptr);
 9     //copy constructor
10     string(const string&);
11     //assign operator
12     string& operator=(const string& rhs);
13     //deconstructor
14     ~string();
15     
16     friend std::ostream& operator<<(std::ostream & os, string &str);    //友元函数可以访问私有成员
17 private:
18     char* m_data;
19 };
20 //构造函数的实现
21 string::string(const char* str)
22 {
23     std::cout << "构造函数被调用\n";
24     if (nullptr == str) {
25         m_data = new char[1];
26         m_data[0] = '\0';
27     }
28     else
29     {
30         m_data = new char[strlen(str) + 1];
31         strcpy(m_data, str);
32     }
33 }
34 //拷贝构造函数的实现
35 string::string(const string& another) {
36     std::cout << "拷贝构造函数被调用:\n";
37     m_data = new char[strlen(another.m_data) + 1];
38     strcpy(m_data, another.m_data);
39 }
40 // 赋值运算
41 string& string::operator=(const string& rhs) {
42     std::cout << "赋值运算符被调用:\n";
43     if (this == &rhs) return *this;
44     delete[]m_data;
45     m_data = new char[strlen(rhs.m_data) + 1];
46     strcpy(m_data, rhs.m_data);
47     return *this;
48 }
49 string::~string()
50 {
51     std::cout << "析构函数被调用:\n";
52     delete[]m_data;
53     m_data = nullptr;
54 }
55 std::ostream& operator<<(std::ostream & os, string& str) {
56     os << str.m_data;
57     return os;
58 }
59 int main() {
60     string str1("jibisheng");
61     string str2("zhangjie");
62     string str3(str1);
63     string str4;
64     str4 = str3;
65     std::cout << str1 << "\n"<<str2<<std::endl<<str3<<std::endl<<str4<<std::endl;
66     return 0;    
67 }

 

标签:面试题,const,string,c++,ostream,operator,include,class
来源: https://www.cnblogs.com/jibisheng/p/13140984.html