Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.52/29: Рейтинг темы: голосов - 29, средняя оценка - 4.52
3 / 3 / 0
Регистрация: 18.01.2016
Сообщений: 198

Массив оценок в классе

18.07.2016, 16:55. Показов 6503. Ответов 24
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
тут создан класс и параметры к нему и
есть метод
C++
1
2
3
4
5
6
7
8
void Student::add()
{
    cout << "введите количество ваших оценок = ";
    cin >> n;
    mass = new int[n];
    for (int i = 0; i < n; i++)
        cin >> mass[i];
}
который создает массив и добавляет значения в него
мне нужно что бы такой же код был и работал в мейне
помогите чет не как не могу правильно сообразить как он будет выглядеть


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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//1.    Реализовать класс Student, который содержит поля для хранения фамилии,
//имени, отчества, даты рождения, домашнего адреса, телефонного номера.
//Также за каждым студентом закреплены 3 динамических массива оценок – 
//зачёты, курсовые работы, экзамены.Обязательные методы : 2 - 3 версии
//конструктора с параметрами, геттеры и сеттеры для всех полей, показ всех данных о студенте.
 
 
#include <time.h>
#include <iostream>
 
using namespace std;
 
class Date
{
 
    int day;
    int month;
    int year;
public:
    Date(int d = 1, int m = 1, int y = 2000) :day(d), month(m), year(y)
    {
    }
    void SetDay(int day)
    {
        this->day = day;
    }
    void SetMonth(int month)
    {
        this->month = month;
    }
    void SetYear(int year)
    {
        this->year = year;
    }
    const int GetDay() const
    {
        return day;
    }
    const int GetMonth() const
    {
        return month;
    }
    const int GetYear() const
    {
        return year;
    }
};
class PHONE
{
 
    int mob;
    int home;
    int work;
public:
    PHONE(int m = 0, int h = 0, int w = 0) :mob(m), home(h), work(w)
    {
    }
    void SetMob(int mob)
    {
        this->mob = mob;
    }
    void SetHome(int home)
    {
        this->home = home;
    }
    void SetWork(int work)
    {
        this->work = work;
    }
    const int GetMob() const
    {
        return mob;
    }
    const int GetHome() const
    {
        return home;
    }
    const int GetWork() const
    {
        return work;
    }
};
 
class Student
{
    char* surname;//фамилия
    char* name;//имья
    char* patronymic;//отчество
    Date birthday;//дата рождения
    char* adress;//домашнего адреса
    PHONE phone;//телефонного номера
 
 
 
    int n;
    int* mass;
public:
 
    void SetSurame(char* surname)
    {
        if (!surname || strlen(surname) == 0)
            return;
 
        if (this->surname != nullptr)
        {
            delete[]this->surname;
        }
 
        this->surname = new char[strlen(surname) + 1];
        strcpy_s(this->surname, strlen(surname) + 1, surname);
    }
 
    void SetName(char* name)
    {
        if (!name || strlen(name) == 0)
            return;
 
        if (this->name != nullptr)
        {
            delete[]this->name;
        }
 
        this->name = new char[strlen(name) + 1];
        strcpy_s(this->name, strlen(name) + 1, name);
    }
 
 
    void SetPatronymic(char* patronymic)
    {
        if (!patronymic || strlen(patronymic) == 0)
            return;
 
        if (this->patronymic != nullptr)
        {
            delete[]this->patronymic;
        }
 
        this->patronymic = new char[strlen(patronymic) + 1];
        strcpy_s(this->patronymic, strlen(patronymic) + 1, patronymic);
    }
 
 
    void SetBirthday(int day, int month, int year)
    {
        birthday.SetDay(day);
        birthday.SetMonth(month);
        birthday.SetYear(year);
    }
 
    void SetAdress(char* adress)
    {
        if (!adress || strlen(adress) == 0)
            return;
 
        if (this->adress != nullptr)
        {
            delete[]this->adress;
        }
 
        this->adress = new char[strlen(adress) + 1];
        strcpy_s(this->adress, strlen(adress) + 1, adress);
    }
 
    void SetPhone(int mob, int home, int work)
    {
        this->phone.SetMob(mob);
        this->phone.SetWork(work);
        this->phone.SetHome(home);
    }
 
 
    //геттеры 
 
 
 
 
    const char* const GetSurname() const
    {
        return surname;
    }
 
    const char* const GetName() const
    {
        return name;
    }
 
    const char* const GetPatronymic() const
    {
        return patronymic;
    }
 
    Date GetBirthday() const
    {
        return birthday;
    }
 
 
    const char* const GetAdress() const
    {
 
        return  adress;
    }
 
    PHONE GetPhone() const
    {
        return phone;
    }
 
 
    //показ всех данных о студенте
    void About()
    {
        cout << "фамилия: " << surname << "\n";
        cout << "имья: " << name << "\n";
        cout << "отчество: " << patronymic << "\n";
        cout << "дата рождения: " << birthday.GetDay() << "." << birthday.GetMonth() << "." << birthday.GetYear() << "\n";
        cout << "домашный адресс: " << "ул. " << adress << "\n";
        cout << "телефонный номер:\n"
            << "моб. номер: " << phone.GetMob() << "\n"
            << "дом. номер: " << phone.GetHome() << "\n"
            << "роб. номер: " << phone.GetWork() << "\n";
        cout << "\n";
    }
 
 
 
    //конструктор по умолчанию
    Student() :surname(""), name(""), patronymic(""), birthday(Date(1, 1, 2000)), adress(""), phone(PHONE(0, 0, 0))
    {
    }
    //2 - 3 версии конструктора с параметрами
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(PHONE(111111111, 4444444, 42323))
    {
 
    }
 
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday, PHONE _Phone) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(_Phone)
    {
 
    }
 
    //главный конструктор 
    Student(char* SN, char* _Name, char* _Patronymic, Date _Birthday, char* _Adress, PHONE _Phone) :
        surname(SN), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress(_Adress), phone(_Phone)
    {
 
    }
 
    ~Student()
    {
        delete mass;
    }
 
    void  add(); // функция ввода елементов
    void show(); // функция вывода на экран
    void  del(int nom); // функция удаляет елемент с массива
    void  elem(int elem); // функция добавляет елемент в массив
};
 
void Student::add()
{
    cout << "введите количество ваших оценок = ";
    cin >> n;
    mass = new int[n];
    for (int i = 0; i < n; i++)
        cin >> mass[i];
}
 
 
void Student::show()
{
    for (int i = 0; i < n; i++)
    {
        cout << mass[i] << " ";
    }
}
 
void Student::del(int nom)
{
    int* arp = new int[n - 1];
    for (int i = 0; i < nom; i++)
        arp[i] = mass[i];
    for (int i = nom - 1; i < n; i++)
        arp[i] = mass[i + 1];
    delete[]mass;
    mass = arp;
    n--;
    mass = new int[n];
    for (int i = 0; i < n; i++)
        mass[i] = arp[i];
    delete[]arp;
    arp = mass;
}
void Student::elem(int elem)
{
    int* temp = new int[n + 1];
 
    for (int i = 0; i < n; i++)
        temp[i] = mass[i];
    delete[]mass;
    temp[n] = elem;
    mass = temp;
    n++;
    mass = new int[n + 1];
    for (int i = 0; i < n + 1; i++)
        mass[i] = temp[i];
    delete[]temp;
    temp = mass;
}
void main()
{
    setlocale(LC_ALL, "Rus");
    Student a("Рубик", "Иван", "Петрович", Date(11, 12, 1887), "Посмитного 33", PHONE(23121, 431344, 42323));
    a.About();
    //  Student b("Романов", "Жора", "Валентинович", { 3, 13, 1877 }, "Поскотного 1", { 2221, 23232, 124142 });
    //  b.About();
 
    cout << "---зачеты---" << endl;
    a.add();
    a.show();
    cout << " - оценки по зачётам" << "\n";
    cout << "введите какую оценку удалить по зачётам" << "\n";
    int nom;
    cin >> nom;
    a.del(nom);
    a.show();
    cout << " - оценки по зачётам" << "\n";
    cout << "---курсовые---" << endl;
    a.add();
    a.show();
    cout << " - оценки по курсовым" << "\n";
    cout << "добавьте оценку по курсовым" << "\n";
    int elem;
    cin >> elem;
    a.elem(elem);
    a.show();
    cout << " - оценки по курсовым" << "\n";
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
18.07.2016, 16:55
Ответы с готовыми решениями:

В классе инициализировать массив, в классе создать функцию вывода массива на экран
Прошу помоши с выводом данных, которые содержаться в массиве, на экраy: Задача: В классе инициализировать массив, в классе создать...

Как добавить в массив студентов динамический массив оценок?
Как?

Гистограмма оценок в классе
Нужно сделать так чтоб в edit вводились числа от 2 до 5 ( зависит от количества учеников если их 15 то и оценок 15 ) и сделать так чтоб...

24
90 / 88 / 33
Регистрация: 20.07.2016
Сообщений: 403
23.07.2016, 21:01
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от Zigoga Посмотреть сообщение
я могу поменять данные
да можете:
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
#include <iostream>
 
//=====================================================
class Student
{
private:
    int s;
 
public:
    Student (int i): s(i)
    {  }
 
    void operator () (Student& b) 
    { 
        int temp = s;
        s = b.s;
        b.s = temp;
    }
 
    int get () const
    { return s; }
};
 
//=====================================================
int main ()
{
    Student s1(1), s2(2);
 
    std::cout << s1.get() << " " << s2.get() << std::endl;
 
    s1(s2);
    std::cout << s1.get() << " " << s2.get() << std::endl;
 
    return 0;
}
Добавлено через 1 минуту
но зачем себе усложнять жизнь, если можно сделать так:
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
#include <iostream>
#include <utility>
 
//=====================================================
class Student
{
private:
    int s;
 
public:
    Student (int i): s(i)
    {  }
 
    /*void operator () (Student& b) 
    { 
        int temp = s;
        s = b.s;
        b.s = temp;
    }*/
 
    int get () const
    { return s; }
};
 
//=====================================================
int main ()
{
    Student s1(1), s2(2);
 
    std::cout << s1.get() << " " << s2.get() << std::endl;
 
    std::swap(s1, s2);
    
    std::cout << s1.get() << " " << s2.get() << std::endl;
 
    return 0;
}
0
3 / 3 / 0
Регистрация: 18.01.2016
Сообщений: 198
25.07.2016, 22:04  [ТС]
это правильно написано а то через return не хочет выводить результат
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
class Group
{
public:
    unsigned int number;
    unsigned int size;
    Student** book;
 
 
Group(int num = 1)
    {
        size = num;
        book = new Student*[size];
    }
     
    Group(unsigned int number, unsigned int size, Student** book)
    {
    }
    ~Group()
    {
        //delete[] *book;
    }
    Group &operator [](int idx)
    {
         
        if (idx < size)
        {
            Student** temp = new Student*[size];
            for (int i = 0; i < size; i++)
                temp[i] = book[i];
            book = new Student*[idx];
            for (int i = 0; i < size; i++)
                book[i] = temp[i];
            delete[]temp;
            size = idx;
        }
        return  book[idx];
         
        
    }
 
};
Добавлено через 1 час 8 минут
ах да забыл класс Student дописать
вот
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#include <time.h>
#include <iostream>
 
using namespace std;
 
class Date
{
 
    int day;
    int month;
    int year;
public:
    Date(int d = 1, int m = 1, int y = 2000) :day(d), month(m), year(y)
    {
    }
    void SetDay(int day)
    {
        this->day = day;
    }
    void SetMonth(int month)
    {
        this->month = month;
    }
    void SetYear(int year)
    {
        this->year = year;
    }
    const int GetDay() const
    {
        return day;
    }
    const int GetMonth() const
    {
        return month;
    }
    const int GetYear() const
    {
        return year;
    }
};
class PHONE
{
 
    int mob;
    int home;
    int work;
public:
    PHONE(int m = 0, int h = 0, int w = 0) :mob(m), home(h), work(w)
    {
    }
    void SetMob(int mob)
    {
        this->mob = mob;
    }
    void SetHome(int home)
    {
        this->home = home;
    }
    void SetWork(int work)
    {
        this->work = work;
    }
    const int GetMob() const
    {
        return mob;
    }
    const int GetHome() const
    {
        return home;
    }
    const int GetWork() const
    {
        return work;
    }
};
 
class Student
{
    char* surname;//фамилия
    char* name;//имья
    char* patronymic;//отчество
    Date birthday;//дата рождения
    char* adress;//домашнего адреса
    PHONE phone;//телефонного номера
 
 
 
 
public:
 
    void SetSurame(char* surname)
    {
        if (!surname || strlen(surname) == 0)
            return;
 
        if (this->surname != nullptr)
        {
            delete[]this->surname;
        }
 
        this->surname = new char[strlen(surname) + 1];
        strcpy_s(this->surname, strlen(surname) + 1, surname);
    }
 
    void SetName(char* name)
    {
        if (!name || strlen(name) == 0)
            return;
 
        if (this->name != nullptr)
        {
            delete[]this->name;
        }
 
        this->name = new char[strlen(name) + 1];
        strcpy_s(this->name, strlen(name) + 1, name);
    }
 
 
    void SetPatronymic(char* patronymic)
    {
        if (!patronymic || strlen(patronymic) == 0)
            return;
 
        if (this->patronymic != nullptr)
        {
            delete[]this->patronymic;
        }
 
        this->patronymic = new char[strlen(patronymic) + 1];
        strcpy_s(this->patronymic, strlen(patronymic) + 1, patronymic);
    }
 
 
    void SetBirthday(int day, int month, int year)
    {
        birthday.SetDay(day);
        birthday.SetMonth(month);
        birthday.SetYear(year);
    }
 
    void SetAdress(char* adress)
    {
        if (!adress || strlen(adress) == 0)
            return;
 
        if (this->adress != nullptr)
        {
            delete[]this->adress;
        }
 
        this->adress = new char[strlen(adress) + 1];
        strcpy_s(this->adress, strlen(adress) + 1, adress);
    }
 
    void SetPhone(int mob, int home, int work)
    {
        this->phone.SetMob(mob);
        this->phone.SetWork(work);
        this->phone.SetHome(home);
    }
 
 
    //геттеры 
 
    const char* const GetSurname() const
    {
        return surname;
    }
 
    const char* const GetName() const
    {
        return name;
    }
 
    const char* const GetPatronymic() const
    {
        return patronymic;
    }
 
    Date GetBirthday() const
    {
        return birthday;
    }
 
 
    const char* const GetAdress() const
    {
 
        return  adress;
    }
 
    PHONE GetPhone() const
    {
        return phone;
    }
 
 
 
 
 
 
    //конструктор по умолчанию
    Student() :surname(""), name(""), patronymic(""), birthday(Date(1, 1, 2000)), adress(""), phone(PHONE(0, 0, 0))
    {
 
    }
 
    //2 - 3 версии конструктора с параметрами
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(PHONE(111111111, 4444444, 42323))
    {
 
    }
 
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday, PHONE _Phone) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(_Phone)
    {
    }
 
    //главный конструктор 
    Student(char* SN, char* _Name, char* _Patronymic, Date _Birthday, char* _Adress, PHONE _Phone) :
        surname(SN), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress(_Adress), phone(_Phone)
    {
 
    }
 
    ~Student()
    {
    }
 
 
};
 
//показ всех данных о студенте
void About(const Student & s)
{
    cout << "фамилия: " << s.GetSurname() << "\n";
    cout << "имья: " << s.GetName() << "\n";
    cout << "отчество: " << s.GetPatronymic() << "\n";
    cout << "дата рождения: " << s.GetBirthday().GetDay() << "." << s.GetBirthday().GetMonth() << "." << s.GetBirthday().GetYear() << "\n";
    cout << "домашный адресс: " << "ул. " << s.GetAdress() << "\n";
    cout << "телефонный номер:\n"
        << "моб. номер: " << s.GetPhone().GetMob() << "\n"
        << "дом. номер: " << s.GetPhone().GetHome() << "\n"
        << "роб. номер: " << s.GetPhone().GetWork() << "\n";
    cout << "\n";
}
Добавлено через 4 минуты
и получается в перегрузке [] мне нужно вывести конкретного студента из конкретной группы по индексу
прошу помогите я что то совсем запутался вот полный код проекта
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
 //4.    В класс Group добавить перегрузку += Student, что добавляет студента в группу.
//А также перегрузить операции «>», «<», « == », « != » для сравнения двух групп по количеству студентов.
 
 
#include <time.h>
#include <iostream>
 
using namespace std;
 
class Date
{
 
    int day;
    int month;
    int year;
public:
    Date(int d = 1, int m = 1, int y = 2000) :day(d), month(m), year(y)
    {
    }
    void SetDay(int day)
    {
        this->day = day;
    }
    void SetMonth(int month)
    {
        this->month = month;
    }
    void SetYear(int year)
    {
        this->year = year;
    }
    const int GetDay() const
    {
        return day;
    }
    const int GetMonth() const
    {
        return month;
    }
    const int GetYear() const
    {
        return year;
    }
};
class PHONE
{
 
    int mob;
    int home;
    int work;
public:
    PHONE(int m = 0, int h = 0, int w = 0) :mob(m), home(h), work(w)
    {
    }
    void SetMob(int mob)
    {
        this->mob = mob;
    }
    void SetHome(int home)
    {
        this->home = home;
    }
    void SetWork(int work)
    {
        this->work = work;
    }
    const int GetMob() const
    {
        return mob;
    }
    const int GetHome() const
    {
        return home;
    }
    const int GetWork() const
    {
        return work;
    }
};
 
class Student
{
    char* surname;//фамилия
    char* name;//имья
    char* patronymic;//отчество
    Date birthday;//дата рождения
    char* adress;//домашнего адреса
    PHONE phone;//телефонного номера
 
 
 
 
public:
 
    void SetSurame(char* surname)
    {
        if (!surname || strlen(surname) == 0)
            return;
 
        if (this->surname != nullptr)
        {
            delete[]this->surname;
        }
 
        this->surname = new char[strlen(surname) + 1];
        strcpy_s(this->surname, strlen(surname) + 1, surname);
    }
 
    void SetName(char* name)
    {
        if (!name || strlen(name) == 0)
            return;
 
        if (this->name != nullptr)
        {
            delete[]this->name;
        }
 
        this->name = new char[strlen(name) + 1];
        strcpy_s(this->name, strlen(name) + 1, name);
    }
 
 
    void SetPatronymic(char* patronymic)
    {
        if (!patronymic || strlen(patronymic) == 0)
            return;
 
        if (this->patronymic != nullptr)
        {
            delete[]this->patronymic;
        }
 
        this->patronymic = new char[strlen(patronymic) + 1];
        strcpy_s(this->patronymic, strlen(patronymic) + 1, patronymic);
    }
 
 
    void SetBirthday(int day, int month, int year)
    {
        birthday.SetDay(day);
        birthday.SetMonth(month);
        birthday.SetYear(year);
    }
 
    void SetAdress(char* adress)
    {
        if (!adress || strlen(adress) == 0)
            return;
 
        if (this->adress != nullptr)
        {
            delete[]this->adress;
        }
 
        this->adress = new char[strlen(adress) + 1];
        strcpy_s(this->adress, strlen(adress) + 1, adress);
    }
 
    void SetPhone(int mob, int home, int work)
    {
        this->phone.SetMob(mob);
        this->phone.SetWork(work);
        this->phone.SetHome(home);
    }
 
 
    //геттеры 
 
    const char* const GetSurname() const
    {
        return surname;
    }
 
    const char* const GetName() const
    {
        return name;
    }
 
    const char* const GetPatronymic() const
    {
        return patronymic;
    }
 
    Date GetBirthday() const
    {
        return birthday;
    }
 
 
    const char* const GetAdress() const
    {
 
        return  adress;
    }
 
    PHONE GetPhone() const
    {
        return phone;
    }
 
 
 
 
 
 
    //конструктор по умолчанию
    Student() :surname(""), name(""), patronymic(""), birthday(Date(1, 1, 2000)), adress(""), phone(PHONE(0, 0, 0))
    {
 
    }
 
    //2 - 3 версии конструктора с параметрами
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(PHONE(111111111, 4444444, 42323))
    {
 
    }
 
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday, PHONE _Phone) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(_Phone)
    {
    }
 
    //главный конструктор 
    Student(char* SN, char* _Name, char* _Patronymic, Date _Birthday, char* _Adress, PHONE _Phone) :
        surname(SN), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress(_Adress), phone(_Phone)
    {
 
    }
 
    ~Student()
    {
    }
 
 
};
 
//показ всех данных о студенте
void About(const Student & s)
{
    cout << "фамилия: " << s.GetSurname() << "\n";
    cout << "имья: " << s.GetName() << "\n";
    cout << "отчество: " << s.GetPatronymic() << "\n";
    cout << "дата рождения: " << s.GetBirthday().GetDay() << "." << s.GetBirthday().GetMonth() << "." << s.GetBirthday().GetYear() << "\n";
    cout << "домашный адресс: " << "ул. " << s.GetAdress() << "\n";
    cout << "телефонный номер:\n"
        << "моб. номер: " << s.GetPhone().GetMob() << "\n"
        << "дом. номер: " << s.GetPhone().GetHome() << "\n"
        << "роб. номер: " << s.GetPhone().GetWork() << "\n";
    cout << "\n";
}
 
 
 
class Group
{
public:
    unsigned int number;
    unsigned int size;
    Student** book;
 
 
 
     
     
 
 
    int GetSred() const
    {
 
        int sum = 0;
        Student ** book = new Student*[size];
        for (int i = 1; i < size; i++)
        {
            sum += i;
        }
        return sum;
    }
 
 
    Group& Group::operator+=(Student& s)//перегрузка оператора+=
    {
        Group temp(*this);    //создание временного массива
        size = temp.size + 1;
        Student ** book = new Student*[size];
 
        for (int i = 0; i < size - 1; i++)
            book[i] = temp.book[i];
        book = temp.book;
        book[size - 1] = new Student(s);
 
        return *this;
    }
 
    //  перегрузка оператора =  
    Group& Group:: operator = (const Student &с)
    {
        Group temp(*this);
        size = temp.size;
        Student ** book = new Student*[size];
        for (int i = 0; i < size - 1; i++)
            book[i] = temp.book[i];
        book = temp.book;
        book[size - 1] = new Student();
 
        return *(this);
    }
 
     
        
     
 
 
    //А также перегрузить операции «>», «<», « == », « != » для сравнения двух групп по количеству студентов.
    bool operator > (const Group& f2)
    {
 
        if (GetSred()> f2.GetSred())
            return true;
        else
            return false;
    }
 
    bool operator < (const Group& f2)
    {
        if (GetSred()  < f2.GetSred())
            return true;
        else
            return false;
    }
    bool operator == (const Group& f2)
    {
 
        if (GetSred() == f2.GetSred())
            return true;
        else
            return false;
    }
    bool operator != (const Group& f2)
    {
 
        if (GetSred() != f2.GetSred())
            return true;
        else
            return false;
    }
 
 
    
    //•   перегруженные операции   ()
    Group & operator() (const Student & s)
    {
 
        Student ** temp = new Student*[size];
        for (int i = 0; i < size; i++)
            temp[i] = book[i];
        temp[size] = new Student(s);
        delete[] book;
        book = temp;
        size++;
        return *this;
    }
 
    
    
    Group(int num = 1)
    {
        size = num;
        book = new Student*[size];
    }
     
    Group(unsigned int number, unsigned int size, Student** book)
    {
        Student ** temp = new Student*[size];
        for (int i = 0; i < size; i++)
            temp[i] = book[i];
        temp[size] = new Student();
        delete[] book;
        book = temp;
         
    }
    ~Group()
    {
        //delete[] *book;
    }
    int &operator [](int idx)
    {
         
         
        /*if (idx < size)
        {
            Student** temp = new Student*[size];
            for (int i = 0; i < size; i++)
                temp[i] = book[i];
            book = new Student*[idx];
            for (int i = 0; i < size; i++)
                book[i] = temp[i];
            delete[]temp;
            size = idx;
        }
        return book[idx];*/
     
     
    }
 
};
 
void show_book(const Group & g)
{
 
    cout << "Group " << g.number << endl << endl;
    for (int i = 0; i < g.size; i++)
 
        About(*g.book[i]);
}
 
void delete_book(Group & g)
{
    for (int i = 0; i < g.size; i++)
        delete g.book[i];
    delete[]g.book;
    g.size = 0;
}
 
void add_contact(Group & g, const Student & s)
{
    Student ** temp = new Student*[g.size + 1];
    for (int i = 0; i < g.size; i++)
        temp[i] = g.book[i];
    temp[g.size] = new Student(s);
    delete[]g.book;
    g.book = temp;
    g.size++;
}
//  перегрузка оператора >> , <<
 
istream & operator >> (istream & ist, Group & t)
{
    int a;
    cout << "Введите номер группи: ";
    ist >> t.number;
    return ist;
}
 
ostream& operator << (ostream& os, const Group& f)
{
    cout << "Group " << f.number << endl << endl;
    for (int i = 0; i < f.size; i++)
 
        About(*f.book[i]);
    return os;
}
 
 
 
 
 
 
 
void main()
{
    setlocale(LC_ALL, "Rus");
    
    Group   a(111, 0, nullptr);
    
    add_contact(a, { "Рубик", "Иван", "Петрович", Date(11, 12, 1887), "Посмитного 33", PHONE(23121, 431344, 42323) });
    add_contact(a, { "Романов", "Жора", "Валентинович", Date(3, 13, 1877), "Поскотного 1",PHONE(2221, 23232, 124142) });
    //•   перегруженные операции   ()
    a({ "111111", "111111", "111111", Date(11, 12, 1887), "1111111 33", PHONE(23121, 431344, 42323) });
    show_book(a);
    
    
    Group temp = a += Student("aaaa", "aaaaa", "aaaaa", Date(11, 11, 1111), "aaaaa 33", PHONE(222, 222, 222));
    show_book(temp);
 
 
    cout << endl;
 
    Group   b = { 121, 0, nullptr };
    add_contact(b, { "Иванов", "Гена","Андреевыч",Date(2, 3, 1785),"Калантаевская 8",PHONE(11111, 22222, 333333) });
    add_contact(b, { "Смирнова", "Елена","Дмитриевна",Date(1, 1, 1989),"Жукова 12",PHONE(12323, 3213, 2014) });
    add_contact(b, { "Андреев", "Игорь", "Петрович",Date(2, 3, 1785), "Соборная 111" ,PHONE(23231, 21236, 1999) });
    show_book(b);
     
    cout << "Group b - " << b.GetSred() << "\t " << "Group a - " << a.GetSred();
 
    cout << endl << endl;
    //  перегрузка оператора =  
    Group c;
    c = a;
    show_book(c);
 
    
     
     
 
 
 
    //А также перегрузить операции «>», «<», « == », « != » для сравнения двух групп по количеству студентов.
 
    cout << boolalpha << (a > b) << endl;
    cout << "---------------------------------\n ";
    cout << boolalpha << (a < b) << endl;
    cout << "---------------------------------\n ";
    cout << boolalpha << (a == b) << endl;
    cout << "---------------------------------\n ";
    cout << boolalpha << (a != b) << endl;
    cout << "---------------------------------\n ";
 
 
 
    /*cin >> a;
    cout << a << '\n';*/
 
     
     
      
     
 
    //  delete_book(a);
    // delete_book(b); 
}
0
3 / 3 / 0
Регистрация: 18.01.2016
Сообщений: 198
25.07.2016, 23:30  [ТС]
получается в перегрузке [] мне нужно вывести конкретного студента из конкретной группы по индексу
прошу помогите я что то совсем запутался вот полный код проекта
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
 //4.    В класс Group добавить перегрузку += Student, что добавляет студента в группу.
//А также перегрузить операции «>», «<», « == », « != » для сравнения двух групп по количеству студентов.
 
 
#include <time.h>
#include <iostream>
 
using namespace std;
 
class Date
{
 
    int day;
    int month;
    int year;
public:
    Date(int d = 1, int m = 1, int y = 2000) :day(d), month(m), year(y)
    {
    }
    void SetDay(int day)
    {
        this->day = day;
    }
    void SetMonth(int month)
    {
        this->month = month;
    }
    void SetYear(int year)
    {
        this->year = year;
    }
    const int GetDay() const
    {
        return day;
    }
    const int GetMonth() const
    {
        return month;
    }
    const int GetYear() const
    {
        return year;
    }
};
class PHONE
{
 
    int mob;
    int home;
    int work;
public:
    PHONE(int m = 0, int h = 0, int w = 0) :mob(m), home(h), work(w)
    {
    }
    void SetMob(int mob)
    {
        this->mob = mob;
    }
    void SetHome(int home)
    {
        this->home = home;
    }
    void SetWork(int work)
    {
        this->work = work;
    }
    const int GetMob() const
    {
        return mob;
    }
    const int GetHome() const
    {
        return home;
    }
    const int GetWork() const
    {
        return work;
    }
};
 
class Student
{
    char* surname;//фамилия
    char* name;//имья
    char* patronymic;//отчество
    Date birthday;//дата рождения
    char* adress;//домашнего адреса
    PHONE phone;//телефонного номера
 
 
 
 
public:
 
    void SetSurame(char* surname)
    {
        if (!surname || strlen(surname) == 0)
            return;
 
        if (this->surname != nullptr)
        {
            delete[]this->surname;
        }
 
        this->surname = new char[strlen(surname) + 1];
        strcpy_s(this->surname, strlen(surname) + 1, surname);
    }
 
    void SetName(char* name)
    {
        if (!name || strlen(name) == 0)
            return;
 
        if (this->name != nullptr)
        {
            delete[]this->name;
        }
 
        this->name = new char[strlen(name) + 1];
        strcpy_s(this->name, strlen(name) + 1, name);
    }
 
 
    void SetPatronymic(char* patronymic)
    {
        if (!patronymic || strlen(patronymic) == 0)
            return;
 
        if (this->patronymic != nullptr)
        {
            delete[]this->patronymic;
        }
 
        this->patronymic = new char[strlen(patronymic) + 1];
        strcpy_s(this->patronymic, strlen(patronymic) + 1, patronymic);
    }
 
 
    void SetBirthday(int day, int month, int year)
    {
        birthday.SetDay(day);
        birthday.SetMonth(month);
        birthday.SetYear(year);
    }
 
    void SetAdress(char* adress)
    {
        if (!adress || strlen(adress) == 0)
            return;
 
        if (this->adress != nullptr)
        {
            delete[]this->adress;
        }
 
        this->adress = new char[strlen(adress) + 1];
        strcpy_s(this->adress, strlen(adress) + 1, adress);
    }
 
    void SetPhone(int mob, int home, int work)
    {
        this->phone.SetMob(mob);
        this->phone.SetWork(work);
        this->phone.SetHome(home);
    }
 
 
    //геттеры 
 
    const char* const GetSurname() const
    {
        return surname;
    }
 
    const char* const GetName() const
    {
        return name;
    }
 
    const char* const GetPatronymic() const
    {
        return patronymic;
    }
 
    Date GetBirthday() const
    {
        return birthday;
    }
 
 
    const char* const GetAdress() const
    {
 
        return  adress;
    }
 
    PHONE GetPhone() const
    {
        return phone;
    }
 
 
 
 
 
 
    //конструктор по умолчанию
    Student() :surname(""), name(""), patronymic(""), birthday(Date(1, 1, 2000)), adress(""), phone(PHONE(0, 0, 0))
    {
 
    }
 
    //2 - 3 версии конструктора с параметрами
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(PHONE(111111111, 4444444, 42323))
    {
 
    }
 
    Student(char* _Surname, char* _Name, char* _Patronymic, Date _Birthday, PHONE _Phone) :
        surname(_Surname), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress("Посмитного 33"), phone(_Phone)
    {
    }
 
    //главный конструктор 
    Student(char* SN, char* _Name, char* _Patronymic, Date _Birthday, char* _Adress, PHONE _Phone) :
        surname(SN), name(_Name), patronymic(_Patronymic), birthday(_Birthday), adress(_Adress), phone(_Phone)
    {
 
    }
 
    ~Student()
    {
    }
 
 
};
 
//показ всех данных о студенте
void About(const Student & s)
{
    cout << "фамилия: " << s.GetSurname() << "\n";
    cout << "имья: " << s.GetName() << "\n";
    cout << "отчество: " << s.GetPatronymic() << "\n";
    cout << "дата рождения: " << s.GetBirthday().GetDay() << "." << s.GetBirthday().GetMonth() << "." << s.GetBirthday().GetYear() << "\n";
    cout << "домашный адресс: " << "ул. " << s.GetAdress() << "\n";
    cout << "телефонный номер:\n"
        << "моб. номер: " << s.GetPhone().GetMob() << "\n"
        << "дом. номер: " << s.GetPhone().GetHome() << "\n"
        << "роб. номер: " << s.GetPhone().GetWork() << "\n";
    cout << "\n";
}
 
 
 
class Group
{
public:
    unsigned int number;
    unsigned int size;
    Student** book;
 
 
 
     
     
 
 
    int GetSred() const
    {
 
        int sum = 0;
        Student ** book = new Student*[size];
        for (int i = 1; i < size; i++)
        {
            sum += i;
        }
        return sum;
    }
 
 
    Group& Group::operator+=(Student& s)//перегрузка оператора+=
    {
        Group temp(*this);    //создание временного массива
        size = temp.size + 1;
        Student ** book = new Student*[size];
 
        for (int i = 0; i < size - 1; i++)
            book[i] = temp.book[i];
        book = temp.book;
        book[size - 1] = new Student(s);
 
        return *this;
    }
 
    //  перегрузка оператора =  
    Group& Group:: operator = (const Student &с)
    {
        Group temp(*this);
        size = temp.size;
        Student ** book = new Student*[size];
        for (int i = 0; i < size - 1; i++)
            book[i] = temp.book[i];
        book = temp.book;
        book[size - 1] = new Student();
 
        return *(this);
    }
 
     
        
     
 
 
    //А также перегрузить операции «>», «<», « == », « != » для сравнения двух групп по количеству студентов.
    bool operator > (const Group& f2)
    {
 
        if (GetSred()> f2.GetSred())
            return true;
        else
            return false;
    }
 
    bool operator < (const Group& f2)
    {
        if (GetSred()  < f2.GetSred())
            return true;
        else
            return false;
    }
    bool operator == (const Group& f2)
    {
 
        if (GetSred() == f2.GetSred())
            return true;
        else
            return false;
    }
    bool operator != (const Group& f2)
    {
 
        if (GetSred() != f2.GetSred())
            return true;
        else
            return false;
    }
 
 
    
    //• перегруженные операции   ()
    Group & operator() (const Student & s)
    {
 
        Student ** temp = new Student*[size];
        for (int i = 0; i < size; i++)
            temp[i] = book[i];
        temp[size] = new Student(s);
        delete[] book;
        book = temp;
        size++;
        return *this;
    }
 
    
    
    Group(int num = 1)
    {
        size = num;
        book = new Student*[size];
    }
     
    Group(unsigned int number, unsigned int size, Student** book)
    {
        Student ** temp = new Student*[size];
        for (int i = 0; i < size; i++)
            temp[i] = book[i];
        temp[size] = new Student();
        delete[] book;
        book = temp;
         
    }
    ~Group()
    {
        //delete[] *book;
    }
    int &operator [](int idx)
    {
         
         
        /*if (idx < size)
        {
            Student** temp = new Student*[size];
            for (int i = 0; i < size; i++)
                temp[i] = book[i];
            book = new Student*[idx];
            for (int i = 0; i < size; i++)
                book[i] = temp[i];
            delete[]temp;
            size = idx;
        }
        return book[idx];*/
     
     
    }
 
};
 
void show_book(const Group & g)
{
 
    cout << "Group " << g.number << endl << endl;
    for (int i = 0; i < g.size; i++)
 
        About(*g.book[i]);
}
 
void delete_book(Group & g)
{
    for (int i = 0; i < g.size; i++)
        delete g.book[i];
    delete[]g.book;
    g.size = 0;
}
 
void add_contact(Group & g, const Student & s)
{
    Student ** temp = new Student*[g.size + 1];
    for (int i = 0; i < g.size; i++)
        temp[i] = g.book[i];
    temp[g.size] = new Student(s);
    delete[]g.book;
    g.book = temp;
    g.size++;
}
//  перегрузка оператора >> , <<
 
istream & operator >> (istream & ist, Group & t)
{
    int a;
    cout << "Введите номер группи: ";
    ist >> t.number;
    return ist;
}
 
ostream& operator << (ostream& os, const Group& f)
{
    cout << "Group " << f.number << endl << endl;
    for (int i = 0; i < f.size; i++)
 
        About(*f.book[i]);
    return os;
}
 
 
 
 
 
 
 
void main()
{
    setlocale(LC_ALL, "Rus");
    
    Group   a(111, 0, nullptr);
    
    add_contact(a, { "Рубик", "Иван", "Петрович", Date(11, 12, 1887), "Посмитного 33", PHONE(23121, 431344, 42323) });
    add_contact(a, { "Романов", "Жора", "Валентинович", Date(3, 13, 1877), "Поскотного 1",PHONE(2221, 23232, 124142) });
    //• перегруженные операции   ()
    a({ "111111", "111111", "111111", Date(11, 12, 1887), "1111111 33", PHONE(23121, 431344, 42323) });
    show_book(a);
    
    
    Group temp = a += Student("aaaa", "aaaaa", "aaaaa", Date(11, 11, 1111), "aaaaa 33", PHONE(222, 222, 222));
    show_book(temp);
 
 
    cout << endl;
 
    Group   b = { 121, 0, nullptr };
    add_contact(b, { "Иванов", "Гена","Андреевыч",Date(2, 3, 1785),"Калантаевская 8",PHONE(11111, 22222, 333333) });
    add_contact(b, { "Смирнова", "Елена","Дмитриевна",Date(1, 1, 1989),"Жукова 12",PHONE(12323, 3213, 2014) });
    add_contact(b, { "Андреев", "Игорь", "Петрович",Date(2, 3, 1785), "Соборная 111" ,PHONE(23231, 21236, 1999) });
    show_book(b);
     
    cout << "Group b - " << b.GetSred() << "\t " << "Group a - " << a.GetSred();
 
    cout << endl << endl;
    //  перегрузка оператора =  
    Group c;
    c = a;
    show_book(c);
 
    
     
     
 
 
 
    //А также перегрузить операции «>», «<», « == », « != » для сравнения двух групп по количеству студентов.
 
    cout << boolalpha << (a > b) << endl;
    cout << "---------------------------------\n ";
    cout << boolalpha << (a < b) << endl;
    cout << "---------------------------------\n ";
    cout << boolalpha << (a == b) << endl;
    cout << "---------------------------------\n ";
    cout << boolalpha << (a != b) << endl;
    cout << "---------------------------------\n ";
 
 
 
    /*cin >> a;
    cout << a << '\n';*/
 
     
     
      
     
 
    //  delete_book(a);
    // delete_book(b); 
}
0
Эксперт С++
 Аватар для hoggy
8973 / 4319 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
26.07.2016, 02:55
очень много ляпов.
и откровенных косяков.

код демонстрирует полное незнание основ с++

логика работы класса Group вызывает удивление


использование виндовс-специфики.
в 297 строке буковка "с" вообще была на русском написана.
утечки памяти.
граммар-конст негодует!
подчеркивания в начале имен - UB.
при запуске вообще все крашеццо.



лекарство:
(насчет бизнес-логики Group я могу ошибаться.
по коду нереально понять,
что имел ввиду аффтар)

http://rextester.com/FXNHL93950

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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#include <cstring>
#include <cstdint>
#include <iostream>
#include <stdexcept>
 
#ifndef OUT_TO_STREAM
    #define OUT_TO_STREAM(type_)  \
        template<class T>friend   \
        ::std::basic_ostream<T>&  \
        operator<<(::std::basic_ostream<T>& os, const type_& obj )
#endif
 
#ifndef FROM_STREAM
#define FROM_STREAM(type_)  \
        template<class T>friend   \
        ::std::basic_istream<T>&  \
        operator>>(::std::basic_istream<T>& is, type_& obj )
#endif
 
 
class Date
{
    uint8_t  day;
    uint8_t  month;
    uint32_t year;
public:
    Date(uint8_t d = 1, uint8_t m = 1, uint32_t y = 2000) 
        :day(d), month(m), year(y)
    {}
 
    void setDay(uint8_t day)    { this->day = day;     }
    void setMonth(uint8_t month){ this->month = month; }
    void setYear(uint32_t year) { this->year = year;   }
    uint8_t  getDay() const     { return this->day;    }
    uint8_t  getMonth() const   { return this->month;  }
    uint32_t getYear() const    { return this->year;   }
};
class Phone
{
    size_t mob;
    size_t home;
    size_t work;
public:
    Phone(int m = 0, int h = 0, int w = 0) 
        :mob(m), home(h), work(w)
    {}
 
    void setMob(size_t mob)   { this->mob = mob;   }
    void setHome(size_t home) { this->home = home; }
    void setWork(size_t work) { this->work = work; }
    size_t getMob()  const    { return this->mob;  }
    size_t getHome() const    { return this->home; }
    size_t getWork() const    { return this->work; }
};
 
class Student
{
public:
    OUT_TO_STREAM(Student)
    {
        os 
           << "фамилия: "  << (obj.getSurname()?    obj.getSurname()   : "неизвестно") << "\n"
           << "имя: "      << (obj.getName()?       obj.getName()      : "неизвестно") << "\n"
           << "отчество: " << (obj.getPatronymic()? obj.getPatronymic(): "неизвестно") << "\n"
 
           << "дата рождения: "   
           << (uint32_t)obj.getBirthday().getDay()   << "."
           << (uint32_t)obj.getBirthday().getMonth() << "." 
           << obj.getBirthday().getYear()  << "\n"
 
           << "домашный адресс: " << "ул. " 
           << (obj.getAdress()? obj.getAdress(): "неизвестно")
           << "\n"
 
           << "телефонный номер:\n"
           << "моб. номер: " << obj.getPhone().getMob()  << "\n"
           << "дом. номер: " << obj.getPhone().getHome() << "\n"
           << "роб. номер: " << obj.getPhone().getWork();
        return os;
    }
 
    Student(
        const char*  surname_    = nullptr, 
        const char*  name_       = nullptr, 
        const char*  patronymic_ = nullptr, 
        const char*  adress_     = nullptr, 
        const Date&  birthday_   = Date(), 
        const Phone& phone_      = Phone()
    ) 
        : surname()
        , name()
        , patronymic()
        , adress()
        , birthday(birthday_)
        , phone(phone_)
    {
        Student::copy_(this->surname   , surname_    );
        Student::copy_(this->name      , name_       );
        Student::copy_(this->patronymic, patronymic_ );
        Student::copy_(this->adress    , adress_     );
    }
 
    Student(const Student& rhs)
        : surname()
        , name()
        , patronymic()
        , adress()
        , birthday(rhs.birthday)
        , phone(rhs.phone)
    { this->copy_(rhs); }
 
    Student(Student&& rhs)
        : surname   (rhs.surname   )
        , name      (rhs.name      )
        , patronymic(rhs.patronymic)
        , adress    (rhs.adress    )
        , birthday  (std::move(rhs.birthday) )
        , phone     (std::move(rhs.phone   ) )
    { this->clear_(std::move(rhs)); }
 
    ~Student()
    {
        delete[] surname;
        delete[] name;
        delete[] patronymic;
        delete[] adress;
    }
 
    const Student& operator=(const Student& rhs)
    {
        this->copy_(rhs);
        this->birthday = rhs.birthday;
        this->phone    = rhs.phone;
        return *this;
    }
 
    const Student& operator=(Student&& rhs)
    {
        this->surname    = rhs.surname   ;
        this->name       = rhs.name      ;
        this->patronymic = rhs.patronymic;
        this->adress     = rhs.adress    ;
        this->birthday   = rhs.birthday  ;
        this->phone      = rhs.phone     ;
 
        this->birthday   = std::move(rhs.birthday);
        this->phone      = std::move(rhs.phone   );
        this->clear_(std::move(rhs));
        return *this;
    }
 
    void setSurame(const char* surname_)       { Student::copy_(this->surname   , surname_   ); }
    void setName(const char* name_)            { Student::copy_(this->name      , name_      ); }
    void setPatronymic(const char* patronymic_){ Student::copy_(this->patronymic, patronymic_); }
    void setAdress(const char* adress_)        { Student::copy_(this->adress    , adress_    ); }
 
    void setBirthday(uint8_t day, uint8_t month, uint32_t year)
    {
        birthday.setDay  (day)  ;
        birthday.setMonth(month);
        birthday.setYear (year) ;
    }
 
    void setPhone(size_t mob, size_t home, size_t work)
    {
        this->phone.setMob (mob) ;
        this->phone.setWork(work);
        this->phone.setHome(home);
    }
 
    const char* const getSurname() const    { return this->surname;    }
    const char* const getName() const       { return this->name;       }
    const char* const getPatronymic() const { return this->patronymic; }
    const char* const getAdress() const     { return this->adress;     }
    const Date& getBirthday() const         { return this->birthday;   }
    const Phone& getPhone() const           { return this->phone;      }
 
private:
    static void copy_(char*& dst, const char* src)
    {
        delete[] dst;
 
        if(!src){
            dst = nullptr;
            return;
        }
 
        const size_t len = strlen(src);
        dst = new char[len + 1];
 
        #ifdef _MSC_VER
            strcpy_s(dst, len + 1, src);
        #else
            strcpy(dst, src);
        #endif
    }
 
    void copy_(const Student& rhs)
    {
        Student::copy_(this->surname,    rhs.surname   );
        Student::copy_(this->name,       rhs.name      );
        Student::copy_(this->patronymic, rhs.patronymic);
        Student::copy_(this->adress,     rhs.adress    );
    }
 
    void clear_(Student&& rhs)
    {
        rhs.surname    = nullptr;
        rhs.name       = nullptr;
        rhs.patronymic = nullptr;
        rhs.adress     = nullptr;
    }
private: 
    char* surname   ;
    char* name      ;
    char* patronymic;
    char* adress    ;
    Date  birthday  ;
    Phone phone     ;
};
 
class Group
{
public:
    OUT_TO_STREAM(Group)
    {
        if(obj.count()==0)
            return os << "Group " << obj.id_group << " : пустая\n";
 
        os << "Group " << obj.id_group << "\n\n";
        for(size_t n = 0; n < obj.size; ++n)
            os << obj.students[n] << "\n\n";
        return os;
    }
    
    FROM_STREAM(Group)
    {
        uint32_t id_group = 0;
        is >> id_group;
        obj.setIDGroup(id_group);
        return is;
    }
    
 
    Group(uint32_t id_group_ = 0)
        : id_group(id_group_)
        , size()
        , students()
    {}
 
    ~Group()
    { 
        delete[] students;
    }
 
    Group(const Group& rhs)
        : id_group(rhs.id_group)
        , size(rhs.size)
        , students()
    { Group::copy_(students, rhs.students, rhs.size); }
 
    Group(Group&& rhs)
        : id_group(std::move(rhs.id_group))
        , size    (std::move(rhs.size    ))
        , students(std::move(rhs.students))
    { Group::clear_(std::move(rhs)); }
 
    const Group& operator=(const Group& rhs)
    {
        size     = rhs.size;
        id_group = rhs.id_group;
        Group::copy_(students, rhs.students, rhs.size);
        return *this;
    }
 
    const Group& operator=(Group&& rhs)
    {
        id_group = rhs.id_group;
        size     = rhs.size    ;
        students = rhs.students;
        Group::clear_(std::move(rhs));
        return *this;
    }
 
    size_t count()const { return size; }
 
    Student& operator[](const size_t indx)
    {
        if(indx>=size)
            throw std::out_of_range("index of student is out of range");
        return students[indx];
    }
 
    void addStudent(const Student& s)
    {
        Student* p = new Student[size + 1];
        for(size_t n=0; n<size; ++n)
            p[n] = std::move(students[n]);
        p[size] = s;
        
        delete[] students;
        students = p;
        ++size;
    }
 
    void addStudent(Student&& s)
    {
        Student* p = new Student[size + 1];
        for(size_t n=0; n<size; ++n)
            p[n] = std::move(students[n]);
        p[size] = std::move(s);
        delete[] students;
        students = p;
        ++size;
    }
 
    template<size_t N> void addStudents(const Student (&group)[N])
    {
        for(size_t n=0;n<N;++n)
            addStudent(group[n]);
    }
 
    void addStudents(const std::initializer_list<Student>& group)
    {
        for(const auto& student: group)
            addStudent(student);
    }
 
    Group& operator()(const Student& s)
    {
        addStudent(s);
        return *this;
    }
 
    Group& operator()(Student&& s)
    {
        addStudent(std::move(s));
        return *this;
    }
 
    Group& operator+=(const Student& s)
    {
        addStudent(s);
        return *this;
    }
 
    Group& operator+=(Student&& s)
    {
        addStudent(std::move(s));
        return *this;
    }
 
 
    bool operator >  (const Group& rhs)const { return size>rhs.size ; }
    bool operator <  (const Group& rhs)const { return size<rhs.size ; }
    bool operator == (const Group& rhs)const { return size==rhs.size; }
    bool operator != (const Group& rhs)const { return size!=rhs.size; }
 
private:
    static void clear_(Group&& rhs)
    {
        rhs.id_group = 0;
        rhs.size     = 0;
        rhs.students = nullptr;
    }
 
    static void copy_(Student*& dst, const Student* src, size_t size)
    {
        delete[] dst;
 
        if(!src)
            return dst = nullptr,void();
 
        dst = new Student[size];
 
        for(size_t n=0 ; n< size; ++n)
            dst[n] = src[n];
    }
private:
    uint32_t id_group;
    size_t   size;
    Student* students;
};
 
void about(const Student& s){ std::cout << s; }
void about(const Group& g)  { std::cout << g; }
 
 
int main()
{
    setlocale(LC_ALL, "Rus");
    
    Group group1(111);
 
    group1.addStudents({
        {"Рубик"   ,"Иван" ,"Петрович"     ,"Посмитного 33", Date(11,12, 1887), Phone(23121,431344,42323 )},
        { "Романов", "Жора", "Валентинович", "Поскотного 1", Date(3 ,13, 1877), Phone(2221 ,23232 ,124142)}
    });
 
    group1 += Student("aaaa", "aaaaa", "aaaaa", "aaaaa 33", Date(11, 11, 1111), Phone(222, 222, 222));
 
    
    group1( {"aaaa", "aaaaa", "aaaaa", "aaaaa 33", Date(11, 11, 1111), Phone(222, 222, 222)} );
 
    std::cout << group1 << "\n---------------------------\n";
 
 
    Group group2{121};
    group1.addStudents({
        { "Иванов"  , "Гена" , "Андреевыч" ,"Калантаевская 8", Date(2, 3, 1785), Phone(11111, 22222, 333333) },
        { "Смирнова", "Елена", "Дмитриевна","Жукова 12"      , Date(1, 1, 1989), Phone(12323, 3213 , 2014)   },
        { "Андреев" , "Игорь", "Петрович"  ,"Соборная 111"   , Date(2, 3, 1785), Phone(23231, 21236, 1999)   }
    });
    std::cout << group2 << "\n---------------------------\n";
 
    Group group3 = group2;
    std::cout << "введите номер группы: ";
    std::cin >> group3;
    std::cout << group3 << "\n---------------------------\n";
 
    std::cout 
         << std::boolalpha << (group1 > group2)  << '\n'
         << "---------------------------------\n"
         << std::boolalpha << (group1 < group2)  << '\n'
         << "---------------------------------\n"
         << std::boolalpha << (group1 == group2) << '\n'
         << "---------------------------------\n"
         << std::boolalpha << (group1 != group2) << '\n'
         << "---------------------------------\n ";
}
0
3 / 3 / 0
Регистрация: 18.01.2016
Сообщений: 198
26.07.2016, 19:02  [ТС]
hoggy, у меня все работает не плохо ну есть ошибки не спорю,
скажите как у вас оператор [] работает чет не пойму
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
26.07.2016, 19:02

Вводя в цикле по 5 оценок каждого студента, подсчитать число студентов, не имеющих оценок 2 и 3
Помогите пожалуйста запутался) Вводя в цикле по 5 оценок каждого студента, подсчитать число студентов, не имеющих оценок 2 и 3. ...

В одном классе нужно создать массив, а в классе program его вывести. "Не все ветви кода возвращают значение"
В одном классе нужно создать массив, а в классе program его вывести, помогите, как разобраться namespace con { class Array ...

Массив оценок в соревнованиях по фигурному катанию
Всем привет, прошу помочь набросать примерный программный код) Оценки, полученные спортсменом в соревнованиях по фигурному катанию (в...

Упорядочить массив по невозрастанию сумм оценок
1) Дан массив записей. Каждая запись содержит сведения о студенте группы: фамилию, оценки по 5 предметам. Упорядочить массив по...

Массив: найти дисциплину с максимальным количеством неудовлетворительных оценок
Помогите, пожалуйста, с написанием кода. Итоговая ведомость студентов за семестр содержит сведения о результатах сдачи экзаменов по всем...


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

Или воспользуйтесь поиском по форуму:
25
Ответ Создать тему
Новые блоги и статьи
Как установить и настроить Windows 11 без подключения к Интернету и без аккаунта Microsoft
Maks 22.11.2026
Положу сюда, чтобы не искать постоянно. • На экране «Давайте подключим вас к сети» во время установки Windows 11 нажмите комбинацию клавиш Shift+F10, чтобы открыть командную строку. Введите. . .
Транслитерация текста с кириллицы на латиницу (вариант №5)
Maks 17.11.2026
Дабы оставить позади все споры о том, какая буква каким образом должна транслитерироваться на латиницу - решил таки доработать данное решение и довести его до мало-мальски логического завершения. . . .
Просмотровщик HLP и конвертер в CHM
Argus19 16.11.2026
Просмотровщик HLP и конвертер в CHM Давно хотел переделать справку Microsoft® Win32® Programmer's Reference, чтобы иметь её под рукой. Но использовать несколько программ не удобно. Искал другие. . .
BitTorrent (версия 7.11 English) и Меню Настройки
russiannick 15.11.2026
Пункты, отвечающие за отключение обновлений в BitTorrent версии 7. 11 (английской) Options Preferences General Language
Транслитерация текста с кириллицы на латиницу (вариант №4)
Maks 15.11.2026
Что-то я перемудрил с предыдущими версиями, в этот раз сделал всё проще, обратившись к функции "СтрокаЛатиницей" из типового общего модуля "СтроковыеФункцииКлиент". В данной функции нет апострофов,. . .
BitTorrent (версия 4.3.9) и Меню Настройки
russiannick 15.11.2026
В меню Настройки можно отключить автоматическое обновление программы. Карта этого меню приложена ниже. Нужный пункт выделен красным. Сервис Настройки Поведение
Транслитерация текста с кириллицы на латиницу (вариант №3)
Maks 15.11.2026
Обновленная версия предыдущей обработки. Изменения коснулись букв: Ъ, Ы, Ь, Э, отображения которых зависят от положения реквизита "Транслитерация имён". Изменено отображение буквы Й. Добавлена. . .
Транслитерация текста с кириллицы на латиницу (вариант №2)
Maks 13.11.2026
Обновленная версия ранее созданной обработки. Добавлено: - Проверка исходного текста на кириллицу, через обращение к стандартной функции "ТолькоКириллицаВСтроке" из общего модуля. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru