Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
АФТИ ООП 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.6k
Лекция № 8. Хорошие и плохие ОО-программы
be9
0
1.5k
Лекция № 7. algorithm. Исключения
be9
1
1.5k
Лекция № 6. Стандартная библиотека C++. Часть 2
be9
0
1.6k
Лекция № 5. Стандартная библиотека C++. Часть 1
be9
0
1.7k
Other Decks in Education
See All in Education
Liburd and Stoll Farrell "Copyright Essentials From A to AI: A 2026 NISO Training Series, Session Two: Fair Use and the Public Domain"
baltimoreniso
0
120
HCI Research Methods - Lecture 7 - Human-Computer Interaction (1023841ANR)
signer
PRO
0
1.8k
Introduction to Primary and Secondary Metabolites their Metabolic Pathways
drpoonamkc
0
190
HCI and Interaction Design - Lecture 2 - Human-Computer Interaction (1023841ANR)
signer
PRO
0
2k
Sanapilvet opetuksessa
matleenalaakso
1
36k
Human Perception and Cognition - Lecture 4 - Human-Computer Interaction (1023841ANR)
signer
PRO
0
1.7k
Design Guidelines and Models - Lecture 5 - Human-Computer Interaction (1023841ANR)
signer
PRO
0
1.7k
人間関係に取り組む、その時に / step away to make space
spring_aki
0
200
【ainiチャット】2段階認証設定方法
ainischool
0
160
人工知能とは/IntroAI02
kfujita
0
120
El Clima de España. Tema 2 (PPT)
juanmartin2026
0
19k
Biologicals & Herbals, and Food & Nutraceuticals
drpoonamkc
0
110
Featured
See All Featured
ラッコキーワード サービス紹介資料
rakko
5
5.8M
Crafting Experiences
bethany
1
430
Jess Joyce - The Pitfalls of Following Frameworks
techseoconnect
PRO
1
470
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
287
14k
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.7k
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
6
1.3k
Fantastic passwords and where to find them - at NoRuKo
philnash
53
4k
Test your architecture with Archunit
thirion
2
2.5k
Thoughts on Productivity
jonyablonski
76
5.5k
A better future with KSS
kneath
240
18k
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
2
3k
Balancing Empowerment & Direction
lara
6
1.4k
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