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
|
#include <iostream>
#include <utility>
#include <algorithm>
#include <initializer_list>
class MyClass {
int* m_data {};
size_t m_size {};
size_t m_used {};
public:
// Default constructor
MyClass() { }
// Constructor
MyClass(size_t size) : m_size(size), m_data(new int[size]) {}
// Constructor - Initializer list
MyClass(const std::initializer_list<int>& il) : m_size(il.size()), m_used(il.size()), m_data(new int[il.size()]) {
std::copy(il.begin(), il.end(), m_data);
}
// Swap
void swap(MyClass& rhs) noexcept {
std::swap(rhs.m_data, m_data);
std::swap(rhs.m_size, m_size);
std::swap(rhs.m_used, m_used);
}
// Copy constructor.
MyClass(const MyClass& rhs) : m_size(rhs.m_size), m_used(rhs.m_used), m_data(new int[rhs.m_size]) {
std::copy_n(rhs.m_data, m_used, m_data);
}
// Assignment operator.
MyClass& operator=(const MyClass& rhs) {
auto tmp {rhs};
swap(tmp);
return *this;
}
// Move constructor.
MyClass(MyClass&& other) noexcept {
swap(other);
}
// Move assignment operator.
MyClass& operator=(MyClass&& other) noexcept {
swap(other);
return *this;
}
~MyClass() {
delete[] m_data;
}
void addData(const std::initializer_list<int>& il) noexcept {
for (auto it = il.begin(); m_used < m_size && it != il.end(); ++it)
m_data[m_used++] = *it;
}
[[nodiscard]]
const int operator[](size_t ind) const {
return m_data[ind];
}
[[nodiscard]]
int& operator[](size_t ind) {
return m_data[ind];
}
void display() const noexcept {
for (size_t i = 0; i < m_used; ++i)
std::cout << m_data[i] << ' ';
std::cout << '\n';
}
};
int main() {
MyClass mc1(7);
MyClass mc2;
mc1.addData({1, 2, 3, 4, 5});
mc1.addData({6, 7, 8, 9});
mc2 = mc1;
mc1.display();
mc2.display();
mc2[3] = 89;
mc2.display();
}
| |