класс пример с++

Программа: Пример класс, конструктор, динамика.

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
#include <iostream>
#include <cstring>
#include <algorithm>
 
class String
{
public:
    String(char const* const p_ = "")
    {
        p = new char[strlen(p_) + 1];
        strcpy(p, p_);
    }
    String(String const& s)
    {
        p = new char[strlen(s.p) + 1];
        strcpy(p, s.p);
    }
    String& operator=(String s)
    {
        Swap(*this, s);
        return *this;
    }
    virtual ~String()
    {
        delete[] p;
        p = 0;
    }
    friend std::ostream& operator<<(std::ostream& ost, String const& s)
    {
        return ost << s.p;
    }
protected:
    char* p;
    void Swap(String& lhs, String& rhs)
    {
        std::swap(lhs.p, rhs.p);
    }
};
 
class DString : public String
{
public:
    explicit DString(char const* const p_ = "", char const* const p1_ = "") : String(p_)
    {
        p1 = new char[strlen(p1_) + 1];
        strcpy(p1, p1_);
    }
    DString(DString const& ds) : String(ds)
    {
        p1 = new char[strlen(ds.p1) + 1];
        strcpy(p1, ds.p1);
    }
    DString& operator=(DString ds)
    {
        Swap(*this, ds);
        return *this;
    }
    ~DString()
    {
        delete[] p1;
        p1 = 0;
    }
    friend std::ostream& operator<<(std::ostream& ost, DString const& s)
    {
        return ost << s.p << '\n' << s.p1;
    }
protected:
    char* p1;
    void Swap(DString& lhs, DString& rhs)
    {
        String::Swap(lhs, rhs);
        std::swap(lhs.p1, rhs.p1);
    }
};
 
int main()
{
    DString ds("aa", "bb");
    String s = ds;
    std::cout << s << std::endl;
    return 0;
}