Upgrade to Pro — share decks privately, control downloads, hide ads and more …

АФТИ ООП 2013-2014. Лекция II/3

АФТИ ООП 2013-2014. Лекция II/3

Oleg Dashevskii

March 03, 2014
Tweet

More Decks by Oleg Dashevskii

Other Decks in Education

Transcript

  1. struct Point {! double x, y, z;! ! Point(double _x,

    double _y, double _z)! : x(_x), y(_y), z(_z) {}! };! ! Point a(10, 20, 30);! Point b(a);! Point c;! Конструктор, определенный 
 пользователем Конструктор копирования
 (неявный) Конструктор по умолчанию
  2. КОНСТРУКТОР КОПИРОВАНИЯ Point zeroPoint() {! return Point(0, 0, 0);! }!

    1. Объект является возвращаемым значением
  3. ВАРИАНТЫ X(const X& copy_from_me);! X(X& copy_from_me);! X(volatile X& copy_from_me);! X(const

    volatile X& copy_from_me);! X(X& copy_from_me, int = 0);! X(const X& copy_from_me, double = 1.0, int = 42);!
  4. struct Point {! double x, y, z;! ! Point(double _x,

    double _y, double _z)! : x(_x), y(_y), z(_z) {}! ! // Do not write this yourself!! Point(const Point &other) :! x(other.x), y(other.y), z(other.z)! {}! };! Такой конструктор можно не писать, 
 он будет сгенерирован автоматически 
 (копирование всех полей)
  5. struct Buffer {! char *buf;! size_t size;! ! Buffer(size_t sz)

    :! buf(new char[sz]), size(sz) {}! ! ~Buffer() { delete buf; }! };!
  6. Buffer::Buffer(const Buffer &other)! : size(other.size)! {! buf = new char[size];!

    if (buf)! memcpy(buf, other.buf, size);! }! Иначе: будет очень-очень плохо!
  7. • Можно перегрузить поведение почти всех операторов, существующих в языке.

    • Нельзя создать новые операторы. • Нельзя повлиять на приоритет, арность или ассоциативность операторов.
  8. A a;! SomeType b;! ! // a + b! !

    class A {! // ...! return_type operator+(SomeType b);! };! ! // b + a ? Оператор-член класса
  9. Оператор-глобальная функция class A {! // ...! friend return_type operator+(const

    A &, SomeType);! friend return_type operator+(SomeType, const A &);! };! ! ! inline return_type operator+(const A &a, SomeType b) {! // ...! }! ! ! inline return_type operator+(SomeType b, const A &a) {! // ...! }!
  10. АРИФМЕТИКА • + - * / % • Можно использовать

    оба варианта функций. • operator- бывает двух видов!
  11. ПОБИТОВЫЕ ОПЕРАЦИИ • ^ | & ~ << >> •

    Приоритет ниже, чем у арифметики:
 a ^ n + b воспримется как a ^ (n + b). • Можно использовать оба варианта функций. • << и >> используются стандартной библиотекой для ввода/вывода.
  12. ostream& operator<<(ostream& out, const Vector2D& vec) { // output! out

    << "(" << vec.x() << ", " << vec.y() << ")";! return out;! }! ! istream& operator>>(istream& in, Vector2D& vec) { // input! double x, y;! // skip opening parenthesis! in.ignore(1);! ! // read x! in >> x;! vec.set_x(x);! ! // skip delimiter! in.ignore(2);! ! // read y! in >> y;! vec.set_y(y);! ! // skip closing parenthesis! in.ignore(1);! ! return in;! }
  13. ОПЕРАТОР ПРИСВАИВАНИЯ • Только метод класса! • Существует реализация по

    умолчанию: копирование всех полей. • Если в классе присутствуют указатели, реализация по умолчанию приносит проблемы.
  14. struct Buffer {! char *buf;! size_t size;! ! Buffer(size_t sz)

    :! buf(new char[sz]), size(sz) {}! ! ~Buffer() { delete buf; }! };!
  15. Buffer &Buffer::operator=(const Buffer &other)! {! delete buf;! ! buf =

    new char[size = other.size];! ! if (buf)! memcpy(buf, other.buf, size);! ! return *this;! } Buffer buf(100), buf2(200);! ! buf = buf; // oops!
  16. Buffer &Buffer::operator=(const Buffer &other)! {! if (this != &other) {!

    delete buf;! ! buf = new char[size = other.size];! if (buf)! memcpy(buf, other.buf, size);! }! ! return *this;! }! Защита от самоприсваивания
  17. ОПЕРАТОРЫ СРАВНЕНИЯ • == != < <= > >= •

    Можно использовать оба варианта функций. • Чтобы не мучаться: • #include <utility> • Определить operator== и operator< • Остальные операторы обеспечит STL
  18. ЛОГИЧЕСКИЕ ОПЕРАТОРЫ • ! && || • При задании operator&&

    теряется свойство «короткого замыкания».
  19. bool Function1() { return false; }! bool Function2();! ! Function1()

    && Function2();! ! //////////////////////////////////! ! MyBool Function3() { return MyBool::FALSE; }! MyBool Function4();! ! bool operator&&(MyBool const &, MyBool const &);! ! Function3() && Function4();! Function2() не будет вызвана, а Function4() – будет!
  20. ПРИСВОЕНИЕ- МОДИФИКАЦИЯ • += -= *= /= %= &= |=

    ^= <<= >>= • Метод класса! • operator+= не генерируется автоматически из operator= и operator+. • Нужно возвращать *this.