1 / 34

Классы -2

Классы -2. Понятие указателя. Динамическая память. p. p. 100. p. . 0. 1. 9. Оператор new. Динамическое выделение памяти – происходит во время выполнения программы. Указатель – переменная, хранящая адрес. Она указывает на определенную область памяти. . Формы new:

davis
Download Presentation

Классы -2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Классы-2

  2. Понятие указателя

  3. Динамическая память

  4. 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

  5. int* pNumbers = newint[10]; int x = pNumbers[0]; // ? delete[] pNumbers; double* m = NULL; C++ double* m = nullptr; C++11

  6. Создание объекта

  7. if (haveMessage) { char* body = newchar[messageSize]; } Время жизни body?

  8. char* GetName() { charstr[20]; . . . returnstr; // ? }

  9. Конструктор с параметрами classTime { intm_hour; intm_min; intm_sec; public: Time(); Time(int hour, int min, int sec); };

  10. 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) { }

  11. Конструктор и деструктор • 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; • } • };

  12. Polynom p1(5); Polynom p2 = p1; Polynom* p1 = new Polynom(5); Polynom* p2 = p1;

  13. Конструктор копирования classCircle { public: Circle(); Circle(intx, int y, intr); Circle(const Circle & obj); private: intx; inty; intr; };

  14. 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; }

  15. Явный вызов конструктора копирования 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;

  16. Неявный вызов конструктора копирования

  17. Deep copy & shallow copy

  18. Конструктор преобразования типа classcString { char* m_str; public: }; cString s1(«Text»); cString s2 = «Text»;

  19. classcString { char* m_str; public: cString(); explicitcString(const char * str); }; cString s1(«Text»); cString s2 = «Text»;

  20. Разделение интерфейса и реализации • 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; • }

  21. Структура проекта

  22. Code review • classtochka • { • public: • inta; • intb; • intf(int A, int B) • { • a = A; b = B; • } • }

  23. classImage • { • unsignedchar* data; • shortsize; • public: • void Inverter(); • voidSendByEmail(std::string address); • }

  24. Константные данные, методыи объекты Константные поля данных classMatrix { double** m_array; constintm_size; public: Matrix(int size); ~Matrix(); }; #include«matrix.h» voidmain() { Matrix m(3); //Matrixm; }

  25. Константные данные инициализируются в каждой версии конструктора через список инициализации. #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; }

  26. Константные объекты classTime { public: Time(inthour, int min, int sec); std::string ToString(); }; voidmain() { constTimenow(12,0,0); str= now.ToString(); }

  27. 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(); }

  28. Mutable-данные • classMatrix • { • double** m; • int rows; • int cols; • public: • DoubleDet() const; • }; • doubleMatrix::Det() const • { • d = ... • returnd; • } constMatrix m; std::cout << m.Det();

  29. 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();

  30. 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();

  31. Перегрузка const-метода class String { char* str; public: String(constchar* s); ~String(); char& At(int index); char At(int index) const; };

  32. #include<cstring> #include”string.h” String::String(constchar* s) { str= newchar[strlen(s) + 1]; std::strcpy(str, s); } String::~String() { delete[] str; }

  33. 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';

More Related