340 likes | 528 Views
Классы -2. Понятие указателя. Динамическая память. p. p. 100. p. . 0. 1. 9. Оператор new. Динамическое выделение памяти – происходит во время выполнения программы. Указатель – переменная, хранящая адрес. Она указывает на определенную область памяти. . Формы new:
E N D
p p 100 p .. 0 1 9 Оператор new Динамическое выделение памяти – происходит во время выполнения программы. Указатель – переменная, хранящая адрес. Она указывает на определенную область памяти. Формы new: int* p = new int(); int* p = new int(100); int* p = new int[10]; Формы delete: delete p; delete[] p; //вызов для массива Правило: количество new = количеству delete
int* pNumbers = newint[10]; int x = pNumbers[0]; // ? delete[] pNumbers; double* m = NULL; C++ double* m = nullptr; C++11
if (haveMessage) { char* body = newchar[messageSize]; } Время жизни body?
char* GetName() { charstr[20]; . . . returnstr; // ? }
Конструктор с параметрами classTime { intm_hour; intm_min; intm_sec; public: Time(); Time(int hour, int min, int sec); };
Time::Time() : m_hour(0), m_min(0), m_sec(0) { } Time::Time(inthour, int min, int sec) : m_hour(hour), m_min(min), m_sec(sec) { }
Конструктор и деструктор • class Polynom • { • float* m_numbers; • intm_size; • public: • Polynom(intsize) : m_size(size) • { • m_numbers = m_size > 0 ? new float[m_size] : NULL; • } • ~Polynom() • { • delete[]m_numbers; • } • };
Polynom p1(5); Polynom p2 = p1; Polynom* p1 = new Polynom(5); Polynom* p2 = p1;
Конструктор копирования classCircle { public: Circle(); Circle(intx, int y, intr); Circle(const Circle & obj); private: intx; inty; intr; };
Circle::Circle() : x(0), y(0), r(0) { } Circle::Circle(intx, inty, intr) : x(x), y(y), //? r(r) { } Circle::Circle(const Circle & obj) { x = ref.x; y = ref.y; r = ref.z; }
Явный вызов конструктора копирования Circle c1; Circle c2(100, 100, 50); Circle c3(c2); Circle* c1 = new Circle(); Circle* c2 = new Circle(100, 100, 50); Circle* c3 = new Circle(*c2); deletec1; deletec2 deletec3;
Неявный вызов конструктора копирования
Конструктор преобразования типа classcString { char* m_str; public: }; cString s1(«Text»); cString s2 = «Text»;
classcString { char* m_str; public: cString(); explicitcString(const char * str); }; cString s1(«Text»); cString s2 = «Text»;
Разделение интерфейса и реализации • class Point • { • double x; • double y; • public: • // Метод установки значений • void Set(double x, double y); • }; • void Point::Set(double x, double y) • { • this->x = x; • this->y = y; • }
Code review • classtochka • { • public: • inta; • intb; • intf(int A, int B) • { • a = A; b = B; • } • }
classImage • { • unsignedchar* data; • shortsize; • public: • void Inverter(); • voidSendByEmail(std::string address); • }
Константные данные, методыи объекты Константные поля данных classMatrix { double** m_array; constintm_size; public: Matrix(int size); ~Matrix(); }; #include«matrix.h» voidmain() { Matrix m(3); //Matrixm; }
Константные данные инициализируются в каждой версии конструктора через список инициализации. #include«Matrix.h» Matrix::Matrix(int size) : m_size(size) { m_size= size; m_array= newdouble*[m_size]; for(int i=0; i < m_size; i++) { m_array[i] = newdouble[m_size]; for(int j=0; j < m_size; j++) array[i][j] = 0; } } Matrix::~Matrix() { for(int i=0; i< size; i++) delete[] m_array[i]; delete[] m_array; }
Константные объекты classTime { public: Time(inthour, int min, int sec); std::string ToString(); }; voidmain() { constTimenow(12,0,0); str= now.ToString(); }
classTime { public: Time(inthour, int min, intsec); std::stringToString() const; }; std::string Time::ToString() const { ... } voidmain() { constTime now(12,0,0); std::string s = now.ToString(); }
Mutable-данные • classMatrix • { • double** m; • int rows; • int cols; • public: • DoubleDet() const; • }; • doubleMatrix::Det() const • { • d = ... • returnd; • } constMatrix m; std::cout << m.Det();
classMatrix • { • double** m; • int rows; • int cols; • doubledet; • boolisDetCalc; • public: • doubledet() const; • }; • doubleMatrix::det() const • { • if (!isDetCalc) det = ... • returndet; • } constMatrix m; std::cout << m.det();
classMatrix • { • double** m; • int rows; • int cols; • mutable doubledet; • mutable boolisDetCalc; • public: • doubledet() const; • }; • doubleMatrix::det() const • { • if (!isDetCalc) det = ... • Returndet; • } constMatrix m; std::cout << m.det();
Перегрузка const-метода class String { char* str; public: String(constchar* s); ~String(); char& At(int index); char At(int index) const; };
#include<cstring> #include”string.h” String::String(constchar* s) { str= newchar[strlen(s) + 1]; std::strcpy(str, s); } String::~String() { delete[] str; }
char& String::At(int index) { returnstr[index]; } charString::At(int index) const { returnstr[index]; } String s1("qwerty"); charc = s1.At(1); s1.At(1) = 'F';