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
良書紹介08_ 頭のいい子がやっているすごいグラフの読み方
bunnchinn3
0
110
「機械学習と因果推論」入門 ⑤ 因果効果推定の一般化
masakat0
0
150
Πλουτοκρατία: Η Τυραννία του Μαμμωνά και η Μεταανθρώπινη Δουλεία
amethyst1
0
270
焦燥を平穏に変えるエンジニアのための哲学
ichimichi
7
5.3k
0415
cbtlibrary
0
230
The Art & Science of Elearning
tmiket
1
230
輻射安全管理系統2.0暨輻防e++學園平台說明會
aecrp
0
1.4k
2026年度春学期 統計学 第6回 データの関係を知る(1)ー 相関関係 (2026. 5. 14)
akiraasano
PRO
0
140
Curso de Consagração ao Sagrado Coração de Jesus - O Sagrado Coração na História (Aula 01)
cm_manaus
0
240
!コスパよくインターンに受かる方法!
ruribou
1
290
Lectura 1 (PIT : Python Basico)
robintux
0
380
Beyond the Prompt: Programming as a Pathway to Statistical Thinking
minecr
0
190
Featured
See All Featured
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
1
6k
Facilitating Awesome Meetings
lara
57
7k
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
0
150
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
480
Amusing Abliteration
ianozsvald
1
220
First, design no harm
axbom
PRO
2
1.2k
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
1
230
A designer walks into a library…
pauljervisheath
211
24k
Taking LLMs out of the black box: A practical guide to human-in-the-loop distillation
inesmontani
PRO
3
2.3k
Building Flexible Design Systems
yeseniaperezcruz
330
40k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
201
75k
The agentic SEO stack - context over prompts
schlessera
0
840
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