Г. Шилтд - Самоучитель C++ (PDF) (1114887), страница 79
Текст из файла (страница 79)
i 11амяти\п";exit(l);len = ob.len;strcpytp, ob.p);return *this;1 1 Индексируемые символы в строкеchar sstrtype: :operator[] (int i){if (i<0 I [ i>len-l) {cout « "ХпЗначение индекса ";cout « i « " выходит за границы массиваЧпexit(l) ;return p[i];1_553_554Самоучитель C++int main(){strtype а("Привет"), b{"Здесь");cout « a.getO « '\n';cout « b.getO « '\n';a = b; // теперь указатель р не перезаписываетсяcout « a. get {) « Лп 1 ;cout « b.getO « '\n';// Доступ к символам посредством индексирования массиваcout « а[0] « а[1] « а[2] « "\п";// Присваивание символов посредством индексирования массиваа[0] = 'X';а[1] = 'Y';а[2] = 'Z';cout « a.get() « "\п";return 0;2.
^include <iostream>^include <cstdlib>using namespace std;class dynarray {int *p;int size;public:dynarray (int s} ;dynarray &operator= (dynarray sob} ;int soperator [ ] {int i) ;// Конструкторdynarray: : dynarray {int s){p = new int [s] ;if(!p) (cout « "Ошибка выделения памятиЛп";exit(l);size = s;ПриложениеВ.Ответынавопросыирешенияупражнений_1.1 Перегрузка оператора = для класса dynarraydynarray sdynarray: :operator= {dynarray sob){int i;if (size! =ob. size} {cout « "Нельзя копировать массивы разных размеров ! \n" ;exit(l) ;for(i=0; i<size; i++) p[i] = ob.p[i];return *this;1// Перегрузка оператора []int Sdynarray: : operator [] (int i){if (i<0 | | i>size) {cout « "ХпЗначение индекса ";cout « i « " выходит за границы массива \п";exit(l) ;}return p[i] ;int main{){int i ;dynarray obi(10), ob2(10}, ob3(100};obl[3] = 10;i = obi[3];cout « i « "\n";ob2 = obi;i = ob2[3];cout « i « "\n";// Выполнение следующей инструкции ведет к ошибкеоЫ = оЬЗ; // присваивание массивов разных размеровreturn 0;Проверка усвоения материала главы 61.
// Перегрузка операторов « и »555556_Самоучитель^include <iostream>using namespace std;class coord {int x, у; // значения координатpublic:coord () { x - 0; у = 0; }coord (int i, int j) { x = i; у = j; }void get_xy(int si/ int &j) { i = x; j = y; )coord operator« (int i) ;coord operator» (int i);// Перегрузка оператора «coord coord: :operator« (int i);\coord temp;temp.x = x « i;temp. у = у « i;return temp;// Перегрузка оператора »coord coord: : operator» (int i){coord temp;temp.x = x » i;temp. у = у » i;return temp;int main (){coord ol (4, 4) , o2;int x, y;o2 = ol « 2; // ob « into2.get_xy (x, y) ;cout « " (ol « 2) X: " « x « ", Y: " « у « "\n";o2 = ol » 2; // ob » into2.get_xy (x, y) ;cout « " (ol » 2) X: " « x « ", Y: " « у « "\n";return 0;C++ПриложениеВ.Ответынавопросыи2.
tinclude <iostream>using namespace std;class three_d {int x, y, z;public:three_d(int i, int j , int k){x = i; y = j ; z = k;}three__d() { x = 0; у = 0; z = 0; }void getfint &i, int &j, int &k)(i = x; j = y; k = z;}three_d operator+ (three_d ob2);three_d operator- (three_d ob2) ;three_d operator++ ( ) ;three_d operator — ( ) ;three_d three_d: :operator+ (three_d ob2)1three_d temp;temp.x = x + ob2.x;temp. у = у 4- ob2.y;temp.z = z-t- ob2.z;return temp;three_d three_d: roperator- (three_d ob2){three_d temp;temp.x = x — ob2.x;temp.
у = у — ob2.y;temp.z = z — ob2.z;return temp;three_d three_d: :operator++{X4-+;return *this;}решенияупражнений_557555Самоучитель C++three__d three_d: : operator — ( ){x— ;у— ;z— ;return *this;}int main(){three_d olUO, 10, 10), o2(2, 3, 4), o3int x, y, z;o3 = ol + o2;оЗ-get (x, y, z) ;cout « " X: " « x « ", Y:cout « Z: " « z « "\n";o3 = ol - o2;o3.get(x, y, z) ;cout « " X: " « x « ", Y:« y;« y;cout « Z: " « z « "\n";ol.get (x, y, z) ;cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";ol.get(x, y, z);cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";return 0;3. #include <iostream>using namespace std;class three_d {int x, y, z;public:three_d(int i, int j, int k)x=i; y=j;}three_d() { x = 0Приложение^ В.
Ответы на вопросы и решения упражненийvoid get (int si, int &j, int &k)i = x; j = y; k = z;three_d operator+{three_d &ob2);three_d operator-{three_d &ob2);friend three_d operator++(three_d &ob) ;friend three_d operator—(three_d Sob);three_d three_d::operator+(three_d &ob2)three_jd temp/temp.x = x + ob2.x;temp.у = у + ob2.y;temp.z = z + ob2.z;return temp;three_d three_d::operator-(three_d sob2)three_d temp;temp.x = x — ob2.x;temp.у = у — ob2.y;temp.z = z — ob2.z;return temp;three d operator++(three d Sob)return ob;}three_d operator—(three_d &ob}{ob.x—;ob.y—;ob.
z —;return ob;559560_СамоучительC++int ma in (}{three_d ol{10, 10, 10), o2(2, 3, 4), o3;int x, y, z;o3 = ol + o2;o3.get(x, y, z);cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";03 = ol - o2;o3.get(x, y, z) ;cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";o l . g e t ( x , y, z) ;cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";— ol;o l . g e t f x , y, z) ;cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";return 0;4. Бинарная оператор- функция — член класса получает левый операнд неявно,через указатель this. Дружественная бинарная оператор-функция явно получает оба операнда. У унарной оператор- функции — члена класса нет явнозаданных параметров.
У дружественной унарной оператор-функции естьодин параметр.5. Перегрузка оператора = может потребоваться, когда применяемого по умолчанию поразрядного копирования недостаточно. Например, вам может понадобиться объект, в котором была бы копия только части данных исходногообъекта.6. Нет.7. ^include <iostream>using namespace std;class three_d {int x, y, z;public:three d(int i,int j,int k)ПриложениеВ.Ответынавопросыирешения^упражнений _ 567{х = i; y= j ; z = k;}three_d() { х = 0; у = 0; z = 0; }void get (int si, int &j, int &k){i = x; j = y; k = z;}friend three_d operator+ (three_d ob, int 1} ;friend three_d operator^- (int i, three_d ob) ;);three_d operator+(three_d ob, int i)(three_d temp;temp.x = ob.x + i;temp. у = ob.y + i;temp. z = ob. z + i;return temp;Ithree_d operator+ (int i, three_d ob){three_d temp;temp .x = ob .
x + i ;temp . у = ob . у + i ;temp.z = ob.z + i;return temp;int main ( )ithread ol(10, 10, 10) ;int x, y, z;ol = ol + 10;ol.getfx, y, z) ;cout « " X: " « x « ", Y: " « y;cout « Z: " « z « "\n";ol = -20 + ol;ol.get (x, y, z) ;cout « " X: " « x « ", Y: " « y;cout « 2,:. " « z « "\n";return 0;Самоучитель C++5628. #include <iostream>using namespace std;class three_d (int x, y, z;public:three_d(int i, int j, int k){x = i; у = j ; z = k;ithree_d() ( x = 0; у = 0; z = 0; }void get (int Si, int &j, int 5k)(i = x; j = y; k = z;}int operator== (three d ob2) ;int operator !=(three_d ob2) ;int operator I I (three_d ob2) ;};int three_d: : opera tor== (three_d ob2){return x==ob2.x &s y==ob2 . у && z==ob2.z;}int three_d: :operator!= (three_d ob2){return x!=ob2.x SS y!=ob2.y s& z!=ob2.z;}int three_d: : operator! I (three_d ob2){return x||ob2.x SS у I I ob2 .
у 5& z||ob2.z;}int main ( ){,three_d ol(10, 10, 10), o2 (2, 3, 4), o3 (0, 0, 0)if(ol==ol) cout « "ol == ol\n";if{ol!=o2) cout « "ol !- o2\n";if(o3||ol) cout « "ol или оЗ равняется истина\пreturn 0;Приложение В. Ответы на вопросы и решения упражнений5639. Оператор [] обычно перегружается для того, чтобы использовать привычныйиндексный синтаксис для доступа к элементам инкапсулированного в классемассива.Проверка усвоения материала в целом1. /* В данной программе для простоты не был реализован контрольошибок. Однако в реально функционирующем приложении такой контрольобязателенV#include <io5tream>#include <cstring>using namespace std;class strtype (char s[80];public:strtypeO { *s - '\0'; }strtype(char *p) { strcpyfs, p); }char *get{) { return s; }strtype operator-t-(strtype s2) ;strtype operator=(strtype s2) ;int operator<(strtype s2);int operator>(strtype s2);int operator=={strtype s2);strtype strtype::operator+(strtype s2){strtype temp;strcpy (ternp.s, s) ;strcpy(temp.s, s2 .s);return temp;1strtype strtype::operator=(strtype s2)(strcpy(s, s2.s);return *this;!int strtype::operator<{strtype s2){return strcmpfs, s2.s) < 0;564СамоучительC++int strtype::operator>(strtype s 2 ){return strcmpfs, s2.s) > 0;}int strtype::operator==(strtype s2),return strcntp(s, s2.s) == 0;}int main (){strtype ol("Привет"), o2(" Здесь"), оЗ;o3 = ol + o2;cout « o3.get() « "\n";o3 = ol;if(ol==o3) cout « "ol равно o3\n";if(ol>o2) cout « "ol > o2\n";if(ol<o2) cout « "ol < o2\n";return 0;ГЛАВА 7Повторение пройденного1.
Нет. Перегрузка оператора просто увеличивает количество типов данных, скоторыми оператор может работать, но не влияет на его исходные свойства.2. Да. Не нужно перегружать операторы только для встроенных типов данныхC++.3. Нет, приоритет оператора изменить нельзя. Нет, нельзя изменить и числооперандов.4. ^include <iostream>using namespace std;class array {int nums[10];public:array {) ;ПриложениеВ.Ответилавопросыирешенияупражнений_.void set (int n[10] ) ;void show () ;array operator-f (array ob2) ;array operator- (array ob2) ;int operator== (array ob2) ;};array: r a r r a y (){int i ;f o r ( i = 0; i < 10; i++) nums [i] = 0;void array: :set (int *n){int i;forfi = 0; i < 10; i++) numsfi] = n[i]}void array: : show (){int i;f o r d = Q; i < 10;cout « nums[i] « ' ';cout « "\n";}array array: :operator+ (array ob2){int i;array temp;for(i=0; i<10; i++} temp.nuras[i] = nurns[i] + ob2.nums[i];return temp;)array array: : operator- (array ob2){int i;array temp;for(i=0; i<10; i++) temp.numsfi] = nums[i] - ob2 .