-
Notifications
You must be signed in to change notification settings - Fork 4
/
DerivedCopy.cc
99 lines (88 loc) · 1.61 KB
/
DerivedCopy.cc
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
///
/// @file DerivedCopy.cc
/// @author yll(1711019653@qq.com)
/// @date 2019-01-28 21:30:17
///
#include<string.h>
#include <iostream>
using std::cout;
using std::endl;
class Base
{
public:
Base()
:_data(nullptr)
{
cout << "Base()" << endl;
}
Base(const char * ptr)
:_data(new char[strlen(ptr) + 1]())
{
strcpy(_data, ptr);
cout << "Base(const char * ptr)" << endl;
}
Base(const Base & rhs)
:_data(new char[strlen(rhs._data)+1]())
{
strcpy(_data, rhs._data);
cout << "Base(const Base & rhs)" << endl;
}
Base & operator=(const Base & base)
{
cout << "Base & operator=(const Base & base)" << endl;
if(this != &base)
{
delete [] _data;
_data = new char [strlen(base._data)+1]();
strcpy(_data, base._data);
}
return *this;
}
friend std::ostream & operator<<(std::ostream & os, const Base & rhs);
~Base()
{
if(_data)
delete [] _data;
cout << "~Base()" << endl;
}
private:
char * _data;
};
std::ostream & operator<<(std::ostream & os, const Base & rhs)
{
os << rhs._data;
return os;
}
class Derived
:public Base
{
public:
Derived(const char * ptr)
:Base(ptr)
{
cout << "Derived()" << endl;
}
friend std::ostream & operator<<(std::ostream & os, const Derived & rhs);
~Derived()
{
cout << "~Derived()" << endl;
}
private:
};
std::ostream & operator<<(std::ostream & os, const Derived & rhs)
{
const Base & base = rhs;//向上转型
os << base;
return os;
}
int main(void)
{
Derived d1("hello");
cout << "d1 = " << d1 << endl;
//Derived d2(d1);
//cout << "d2 = " << d2 << endl;
Derived d2("world");
d2 = d1;
cout << "d2 = " << d2 << endl;
return 0;
}