C++梁哥笔记day13 | 我的日常分享

C++梁哥笔记day13

类与对象

一、自定义一个string类myString

对运算符重载以及之前所学的复习

myString.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using namespace std;

class myString
{
friend ostream& operator<<(ostream& out,myString ob);
private:
char *str;
int m_length;
public:
myString();
myString(const char *str);
~myString();
myString(const myString &ob);
int length();
myString& operator=(myString &ob);
};

#endif // MYSTRING_H

myString.cpp

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
#include "mystring.h"
#include<iostream>
#include<string.h>

myString::myString()
{
this->str = NULL;
this->m_length = 0;
cout<<"无参构造方法"<<endl;
}

myString::myString(const char *str)
{
this->str = new char[strlen(str) + 1];
strcpy(this->str,str);
this->m_length = strlen(str);
cout<<"构造方法myString::myString(const char *str)"<<endl;
}

myString::~myString()
{
if(this->str != NULL){
delete [] this->str;
this->str = NULL;
}
cout<<"析构函数~myString()"<<endl;
}

myString::myString(const myString &ob)
{
this->str = new char[ob.m_length + 1];
strcpy(this->str,ob.str);
this->m_length = ob.m_length;
cout<<"拷贝构造函数myString(const myString &ob)"<<endl;
}

int myString::length()
{
return this->m_length;
}

myString &myString::operator=(myString &ob)
{
if(this->str != NULL){
delete [] this->str;
this->str = NULL;
}
this->str = new char[ob.m_length + 1];
strcpy(this->str,ob.str);
this->m_length = ob.m_length;
}

ostream& operator<<(ostream& out,myString ob){
out<<ob.str;
return out;
}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include "mystring.h"
using namespace std;

int main(int argc, char *argv[])
{
myString str1("hello str1");
cout<<"str1:"<<str1<<",length:"<<str1.length()<<endl;

myString str2 = str1;
cout<<"str2:"<<str2<<",length:"<<str2.length()<<endl;

myString str3;
str3 = str1;
cout<<"str3:"<<str3<<",length:"<<str3.length()<<endl;

myString str4 = "hello str4";//隐式转化调用有参构造str4("hello str4") --> str4 = myString("hello str4")
cout<<"str4:"<<str4<<",length:"<<str4.length()<<endl;
return 0;
}

运行结果:
图片

未写完整,还有一些功能可以去完善