Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/6: Рейтинг темы: голосов - 6, средняя оценка - 4.50
0 / 0 / 0
Регистрация: 21.12.2010
Сообщений: 14

overload функции

19.03.2011, 00:15. Показов 1319. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
єсть клас оверлоадових опрераторов, но никак не виходит вивести то что они делают на екран..

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
//main.cpp
#include "HugeInt.h"
#include <conio.h>
#include <time.h>
 
int main()
{
    srand(time(NULL));
    HugeInt a(5);
    a.Rindomize(5);
 
    HugeInt b(7);
    b.Rindomize(5);
 
    HugeInt c;
    
    cout<<a;
    
    getch();
    return 0;
}
 
//HugeInt.h
#include <iostream>
#include <stdlib.h>
using namespace std;
class HugeInt
{
    int*ptr;
    int size;
public:
    HugeInt(int s=10);
    HugeInt(HugeInt &arr);
    virtual~HugeInt();
 
    void Rindomize(int num = 10);
    HugeInt &operator-(HugeInt &arr);
    HugeInt &operator= (HugeInt &arr);
    HugeInt &operator-=(HugeInt &arr);
    bool HugeInt::operator> (HugeInt& arr);
 
};
 //HugeInt.cpp
#include "HugeInt.h"
 
 HugeInt::HugeInt(int s)
{
    size = s;
    ptr = new int[size];
    for(int i = 0; i < size; i++)
    {
        ptr[i] = 0;
    }
    cout << "Constructor" << endl;
}
//--------------------------------------------------------------------------------
HugeInt::HugeInt(HugeInt& arr)
{ 
    size = arr.size;
    ptr = new int[size];
    for(int i = 0; i < size; i++)
    {
        ptr[i] = arr.ptr[i];
        
    }
    cout << "Copy Constructor" << endl;
}
//--------------------------------------------------------------------------------
HugeInt::~HugeInt()
{
    delete[] ptr;
    cout << "Destructor" << endl;
}
//--------------------------------------------------------------------------------
void HugeInt::Rindomize(int num)
{   
    for(int i = 0; i < size; i++)
    {
        ptr[i] = rand() % num;
    }   
}
//--------------------------------------------------------------------------------
HugeInt& HugeInt::operator-(HugeInt& arr) 
{
    int mins = (size < arr.size) ? size : arr.size;     
    HugeInt temp;
    if(mins == arr.size)
    {
        temp = *this;
        for(int i = 0; i < mins; i++)
        {       
            temp.ptr[i] -= arr.ptr[i];
        }
    }
    else
    {   
        temp = arr;
        for(int i = 0; i < mins; i++)
        {       
            temp.ptr[i] -= ptr[i];
        }       
    }
    cout << "Operator -" << endl;
    return temp;
}
//--------------------------------------------------------------------------------
HugeInt&HugeInt::operator= (HugeInt& arr)
{
    if(this != &arr)
    {
        delete[] ptr;
        size = arr.size;
        ptr = new int[size];
        for(int i = 0; i < size; i++)
        {
            ptr[i] = arr.ptr[i];
        }
    }
    cout << "Operator =" << endl;
    return *this;
}
//--------------------------------------------------------------------------------
HugeInt& HugeInt::operator-= (HugeInt& arr)
{
    HugeInt temp;
    temp = *this - arr;
    *this = temp;
    return *this;
}
//--------------------------------------------------------------------------------
bool HugeInt::operator> (HugeInt& arr)
{
        bool result = false;
        if (this->size > arr.size) {
                result = true;
        } else if (this->size == arr.size) {
                for(int i = 0; i < arr.size; i++)
                {       
                                if (this->ptr[i] > arr.ptr[i]) {
                                        result = true;
                                        break;
                                } else if (this->ptr[i] < arr.ptr[i]){
                                        result = false;
                                        break;
                                } else {
                                        result = false;
                                }
                }
        }else{
                result = false;
        }
        return result;
}
просто надо штото з main.cpp зделать пусть будет вивод етих функций, ибо cout<<a; не канаєт
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
19.03.2011, 00:15
Ответы с готовыми решениями:

вызов функции overload
Что я делаю не так, где ошибка? . #include &quot;stdafx.h&quot; #include&lt;iostream&gt; #include&lt;conio.h&gt; using namespace std; int...

operator+ overload
#include &lt;iostream&gt; class point { private: int x; int y; public:

Перегрузка (Overload)
Здравствуйте, форумчане!:) Помогите, пожалуйста, реализовать 2 задачи с уже имеющейся программой. 1. Перегрузку (overload). Я так и не...

2
В астрале
Эксперт С++
 Аватар для ForEveR
8049 / 4806 / 655
Регистрация: 24.06.2010
Сообщений: 10,562
19.03.2011, 00:21
Еще бы... Оператор вывода то не перегружен...

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//main.cpp
#include "HugeInt.h"
#include <conio.h>
#include <time.h>
 
int main()
{
        srand(time(NULL));
        HugeInt a(5);
        a.Rindomize(5);
 
        HugeInt b(7);
        b.Rindomize(5);
 
        HugeInt c;
        
        cout<<a;
        
        getch();
        return 0;
}
 
//HugeInt.h
#include <iostream>
#include <stdlib.h>
using namespace std;
class HugeInt
{
        int*ptr;
        int size;
public:
        HugeInt(int s=10);
        HugeInt(HugeInt &arr);
        virtual~HugeInt();
 
        void Rindomize(int num = 10);
        HugeInt &operator-(HugeInt &arr);
        HugeInt &operator= (HugeInt &arr);
        HugeInt &operator-=(HugeInt &arr);
        bool HugeInt::operator> (HugeInt& arr);
        friend std::ostream& operator <<(std::ostream&, const HugeInt&); 
};
 //HugeInt.cpp
#include "HugeInt.h"
 
 HugeInt::HugeInt(int s)
{
        size = s;
        ptr = new int[size];
        for(int i = 0; i < size; i++)
        {
                ptr[i] = 0;
        }
        cout << "Constructor" << endl;
}
//--------------------------------------------------------------------------------
HugeInt::HugeInt(HugeInt& arr)
{ 
        size = arr.size;
        ptr = new int[size];
        for(int i = 0; i < size; i++)
        {
                ptr[i] = arr.ptr[i];
                
        }
        cout << "Copy Constructor" << endl;
}
//--------------------------------------------------------------------------------
HugeInt::~HugeInt()
{
        delete[] ptr;
        cout << "Destructor" << endl;
}
//--------------------------------------------------------------------------------
void HugeInt::Rindomize(int num)
{       
        for(int i = 0; i < size; i++)
        {
                ptr[i] = rand() % num;
        }       
}
//--------------------------------------------------------------------------------
HugeInt& HugeInt::operator-(HugeInt& arr) 
{
        int mins = (size < arr.size) ? size : arr.size;         
        HugeInt temp;
        if(mins == arr.size)
        {
                temp = *this;
                for(int i = 0; i < mins; i++)
                {               
                        temp.ptr[i] -= arr.ptr[i];
                }
        }
        else
        {       
                temp = arr;
                for(int i = 0; i < mins; i++)
                {               
                        temp.ptr[i] -= ptr[i];
                }               
        }
        cout << "Operator -" << endl;
        return temp;
}
//--------------------------------------------------------------------------------
HugeInt&HugeInt::operator= (HugeInt& arr)
{
        if(this != &arr)
        {
                delete[] ptr;
                size = arr.size;
                ptr = new int[size];
                for(int i = 0; i < size; i++)
                {
                        ptr[i] = arr.ptr[i];
                }
        }
        cout << "Operator =" << endl;
        return *this;
}
//--------------------------------------------------------------------------------
HugeInt& HugeInt::operator-= (HugeInt& arr)
{
        HugeInt temp;
        temp = *this - arr;
        *this = temp;
        return *this;
}
//--------------------------------------------------------------------------------
bool HugeInt::operator> (HugeInt& arr)
{
        bool result = false;
        if (this->size > arr.size) {
                result = true;
        } else if (this->size == arr.size) {
                for(int i = 0; i < arr.size; i++)
                {       
                                if (this->ptr[i] > arr.ptr[i]) {
                                        result = true;
                                        break;
                                } else if (this->ptr[i] < arr.ptr[i]){
                                        result = false;
                                        break;
                                } else {
                                        result = false;
                                }
                }
        }else{
                result = false;
        }
        return result;
}
 
std::ostream& operator <<(std::ostream& os, const HugeInt& Arr)
{
    for(int i=0; i<Arr.size; ++i)
        os<<Arr.ptr[i]<<'\n';
    return os; 
}
1
0 / 0 / 0
Регистрация: 21.12.2010
Сообщений: 14
19.03.2011, 01:06  [ТС]
Спасиба)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
19.03.2011, 01:06
Помогаю со студенческими работами здесь

Friend function and Overload <<(>>)
#include &lt;iostream&gt; using namespace std; class array{ private: unsigned int size; int *mas; public: array(unsigned...

Как заМАКРОсить с темже именем (МАКРОС overload)
Как исхитриться с этим макросом, чтоб можножно было для одного имени S передавать или один или два аргумента #define S(x) printf(&quot;%s...

Неявные приведения типов, error: ambiguous overload for ‘operator=’
Всем привет! Как заставить код работать без костыля? https://rextester.com/SHUYH87895 #include &lt;iostream&gt; ...

Ambiguous overload for 'operator+' (operand types are 'int' and 'Rational')
Решал задачку, все делал по презентации. Создал класс рациональных чисел. Нужно перегрузить операторы +, - и т.д. для собственного класса,...

Странная перегрузка операторов (Error: ambiguous overload for 'operator[]')
Что-то я туплю. Есть код: #include&lt;string&gt; struct test { int operator(const std::string&amp;)const{return 0;} operator...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
Загрузка PNG с альфа-каналом на SDL3 для Android: с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 28.01.2026
Содержание блога SDL3 имеет собственные средства для загрузки и отображения PNG-файлов с альфа-каналом и базовой работы с ними. В этой инструкции используется функция SDL_LoadPNG(), которая. . .
Загрузка PNG с альфа-каналом на SDL3 для Android: с помощью SDL3_image
8Observer8 27.01.2026
Содержание блога SDL3_image - это библиотека для загрузки и работы с изображениями. Эта пошаговая инструкция покажет, как загрузить и вывести на экран смартфона картинку с альфа-каналом, то есть с. . .
Влияние грибов на сукцессию
anaschu 26.01.2026
Бифуркационные изменения массы гриба происходят тогда, когда мы уменьшаем массу компоста в 10 раз, а скорость прироста биомассы уменьшаем в три раза. Скорость прироста биомассы может уменьшаться за. . .
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru