Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
АФТИ ООП 2013-2014. Лекция II/4
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Oleg Dashevskii
March 10, 2014
Education
150
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
АФТИ ООП 2013-2014. Лекция II/4
Oleg Dashevskii
March 10, 2014
More Decks by Oleg Dashevskii
See All by Oleg Dashevskii
Лекция № 13. Практическое руководство по разработке
be9
0
1.6k
Лекция № 12. Ещё о проектировании
be9
0
1.5k
Лекция № 11. Принцип отделения интерфейса. «Малое ООП»
be9
0
1.6k
Лекция № 10. Графическая нотация. Принципы LSP и DIP
be9
0
1.6k
Лекция № 9. Отношения между классами. Принцип открытия-закрытия
be9
0
1.5k
Лекция № 8. Хорошие и плохие ОО-программы
be9
0
1.5k
Лекция № 7. algorithm. Исключения
be9
1
1.5k
Лекция № 6. Стандартная библиотека C++. Часть 2
be9
0
1.6k
Лекция № 5. Стандартная библиотека C++. Часть 1
be9
0
1.6k
Other Decks in Education
See All in Education
BITCOIN : Les fondamentaux !
rlifchitz
0
220
アラムコSTEAMチャレンジ 実践報告書
codeforeveryone
0
200
新しいJavaを学んで・使っていこう! / osd26do
gishi_yama
0
210
2026年度春学期 統計学 第14回 分布についての仮説を検証する ― 仮説検定(1) (2026. 7. 2)
akiraasano
PRO
0
130
Info Session MSc Computer Science & MSc Applied Informatics
signer
PRO
0
300
私たちはなんでテストするんだっけ? Ver.東北IT物産展2026 in 会津若松
camel_404
3
150
Center for Entrepreneurship Education | Science Tokyo (Institute of Science Tokyo)
sciencetokyo
PRO
0
210
Throw Yourself In! - How I've learned English and What I'm Facing
georgeorge
1
220
形骸化しない社内勉強会の取り組み - オーナーシップの作り方 / In-house study session
soudai
PRO
0
160
Laura Wilson - The Quarterly PR Pivot
laurawilsonbseo1
1
390
2026年度春学期 統計学 第8回(オンデマンド配信回) 演習(1)・問題に対する答案の書き方 (2026. 5. 21)
akiraasano
PRO
0
170
Catecismo 26 #1 - Aula inaugural
cm_manaus
0
230
Featured
See All Featured
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
790
Code Review Best Practice
trishagee
74
20k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
520
YesSQL, Process and Tooling at Scale
rocio
174
15k
Visualization
eitanlees
152
17k
Java REST API Framework Comparison - PWX 2021
mraible
34
9.6k
Paper Plane
katiecoart
PRO
2
52k
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
490
First, design no harm
axbom
PRO
2
1.2k
Typedesign – Prime Four
hannesfritz
42
3.1k
[SF Ruby Conf 2025] Rails X
palkan
2
1.3k
VelocityConf: Rendering Performance Case Studies
addyosmani
332
25k
Transcript
ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ Лекция № 2/4 10.03.2014 г.
ОПЕРАТОРЫ ИНКРЕМЕНТА И ДЕКРЕМЕНТА SomeValue& SomeValue::operator++() // prefix! {! ++data;!
return *this;! }! ! SomeValue SomeValue::operator++(int unused) // postfix! {! SomeValue result = *this;! ++data;! return result;! }! SomeValue v;! ! ++v; // prefix! v++; // postfix
// postfix! SomeValue SomeValue::operator++(int unused)! {! SomeValue result = *this;!
++(*this); // call SomeValue::operator++()! return result;! }! Реализация постфиксного оператора через префиксный
• Должен быть членом класса. • Допустим один аргумент, зато
любого типа. • Обычно переопределяется две версии: c const и без. ОПЕРАТОР ИНДЕКСА
template <typename T>! class StupidVector {! // 100 elements ought
to be enough for everyone!! T array[100];! public:! // ...! T &operator[](size_t idx) {! return array[idx];! }! ! const T &operator[](size_t idx) const {! return array[idx];! }! };
template <typename T>! class Matrix;! ! template <typename T>! class
MatrixColumn {! public:! MatrixColumn(Matrix *m, size_t r)! : matrix(m), row(r) {}! ! T &operator[](int col) {! return matrix->element(row, col);! }! ! Matrix *matrix;! size_t row;! };! ! template <typename T>! class Matrix {! public:! Matrix(int rows, int cols);! ! // ...! ! T &element(int row, int col); ! ! MatrixColumn<T> operator[](int row) {! return MatrixColumn<T>(this, row);! }! }; Matrix<double> mat(3, 3);! ! mat[2][2] = 10;
ОПЕРАТОР ВЫЗОВА ФУНКЦИИ • operator() должен быть членом класса, других
ограничений нет. • Активно используется в STL для создания функторов. • std::unary_function • std::binary_function • …
template <class _Arg, class _Result>! struct unary_function {! typedef _Arg
argument_type;! typedef _Result result_type;! };! ! template <class _Arg1, class _Arg2, class _Result>! struct binary_function {! typedef _Arg1 first_argument_type;! typedef _Arg2 second_argument_type;! typedef _Result result_type;! };! ! template <class _Tp>! struct plus : public binary_function<_Tp, _Tp, _Tp> {! _Tp operator()(const _Tp& __x, const _Tp& __y) const {! return __x + __y;! }! };! ! template <class _Tp>! struct negate : public unary_function<_Tp, _Tp> {! _Tp operator()(const _Tp& __x) const {! return -__x;! }! };
#include <iostream>! #include <functional>! #include <algorithm>! ! using namespace std;!
! int main () {! int numbers[] = {10, -20, -30, 40, -50};! int cx;! cx = count_if(numbers, numbers+5, bind2nd(less<int>(),0));! cout << "There are " << cx << " negative elements.\n";! return 0;! }!
ОПЕРАТОРЫ, СВЯЗАННЫЕ С УКАЗАТЕЛЯМИ • operator& • operator* •
operator->
template <typename T>! class undeletable_pointer {! public:! undeletable_pointer(T *ptr) :
base(ptr) {}! // ...! private:! void operator delete(void *);! T *base;! };! ! struct SomeObject {! typedef undeletable_pointer<SomeObject> undeletable_ptr;! ! undeletable_ptr operator&() { return this; }! };!
• Должен возвращать указатель. ! a->b транслируется как (a.operator->())->b;
operator->
class Err {};! ! class Giant {};! ! class Big
{! public:! Big() { throw Err(); }! };! ! class MyClass {! Giant *giant;! Big *big;! public:! MyClass(): giant(new Giant()), big(new Big()) {}! ! ~MyClass() { delete giant; delete big; }! };! ! int main()! {! try {! MyClass myobject;! } catch (Err) {}! ! return 0;! }! К «умным» указателям (smart pointer) Решение: заменить указатели объектами с объявленными деструкторами
template <typename T>! class SmartPtr {! T *ptr;! public:! SmartPtr(T
*p) : ptr(p) {};! T& operator*() { return *ptr; }! T* operator->() { return ptr; }! ! ~SmartPtr() {! delete ptr;! }! };! Первое приближение
template <typename T>! class SmartPtr {! T *ptr;! public:! explicit
SmartPtr(T *p = 0) : ptr(p) {}! T& operator*() const { return *ptr; }! T* operator->() const { return ptr; }! ! SmartPtr(SmartPtr<T> &other) : ptr(other.release()) {}! ! SmartPtr operator=(SmartPtr<T>& other) {! if (this != &other)! reset(other.release());! return *this;! }! ! ~SmartPtr() { delete ptr; }! ! T *release() {! T *oldPtr = ptr;! ptr = 0;! return oldPtr;! }! ! void reset(T *newPtr) {! if (ptr != newPtr) {! delete ptr;! ptr = newPtr;! }! }! };
ОПЕРАТОР ЗАПЯТАЯ • Позволяет делать интересные вещи, например: ! !
• https://gist.github.com/be9/9459195 // Blitz++! Array<int,2> A(3,3);! ! A = 1, 0, 0,! 0, 1, 0,! 0, 0, 1;!
ПРЕОБРАЗОВАНИЕ ТИПА class Y {! // ...! };! ! ostream
&operator<<(ostream &os, const Y &y);! ! class X {! // ...! operator bool() const;! operator Y() const;! };! ! X x;! if (x) {! // ...! }! ! Y y(x);! cout << x;
class Point2D {! int x;! int y;! public:! Point2D(int p,
int q) : x(p), y(q) {}! friend class Point3D;! };! ! class Point3D {! int x;! int y;! int z;! public:! Point3D(int p, int q, int r) : x(p), y(q), z(r) {}! Point3D(const Point2D &point2D) :! x(point2D.x), y(point2D.y), z(0) {}! ! friend ostream& operator<<(ostream& os, const Point3D& point);! };! ! ostream& operator<<(ostream& os, const Point3D& point) {! os << "(" << point.x <<", " << point.y << ", " << point.z << ")";! return os;! }! ! int main() {! Point2D point2D(3, 4);! cout << point2D << endl;! return 0;! }!
ПРАВИЛА • Если у класса объявлен конструктор с одним аргументом,
компилятор может делать «преобразование типа» путем создания временного объекта. • Ключевое слово explicit запрещает компилятору преобразовывать типы.
void f(const Y &);! ! class Y {! Y(const X
&);! };! ! X x;! f(x);! ! /////////////////! ! class Array {! public:! Array(int size);! };! ! Array a('?'); void f(const Y &);! ! class Y {! explicit Y(const X &);! };! ! X x;! f(x); // error! ! /////////////////! ! class Array {! public:! explicit Array(int size);! };! ! Array a('?'); // error
ОПЕРАТОРЫ, СВЯЗАННЫЕ С ПАМЯТЬЮ • operator new • operator
new[] • operator delete • operator delete[] • Требуют аккуратности и очень прямых рук, поэтому мы их рассматривать не будем :)
ОПЕРАТОРЫ, КОТОРЫЕ НЕЛЬЗЯ ПЕРЕГРУЗИТЬ • ? : (тернарный) • .
(доступ к члену класса) • .* (доступ к члену класса по указателю) • :: (namespace) • sizeof • typeid