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

Поиск по классу с полями char* для массива обьектов class a[i]

05.10.2014, 15:18. Показов 639. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Есть класс:
aero.h
Кликните здесь для просмотра всего текста

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
#ifndef AERO_H
#define AERO_H
#include <string>
using namespace std;
 
class aero
{
private:
    char *destination;
    int destination_size;
    char *numberofplane;
    int numberofplane_size;
    char *typeofplane;
    int typeofplane_size;
    float departure;
public:
    aero(){}
    aero(char *cur_destination, char *cur_numberofplane, char *cur_typeofplane, float cur_departure) : destination(cur_destination)
                                                                                                , numberofplane(cur_numberofplane)
                                                                                                , typeofplane(cur_typeofplane)
                                                                                                , departure(cur_departure){}
    void set_destination(char *cur_destination, int size);
    char *get_destination();
 
    void set_numberofplane(char *cur_numberofplane, int size);
    char *get_numberofplane();
 
    void set_typeofplane(char *cur_typeofplane, int size);
    char *get_typeofplane();
 
    void set_departure(float cur_departure);
    float get_departure();
 
    void dialogue(aero defaultAero, aero *plane, char *new_destination, char *new_numberofplane, char *new_typeofplane, float new_departure);
    void print();
};
#endif // AERO_H

aero.cpp
Кликните здесь для просмотра всего текста
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
#define _CRT_SECURE_NO_WARNINGS
#include "aero.h"
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
void aero::set_destination(char *data, int data1)
{
    //delete destination;
    destination = new char[data1];
    strcpy(destination,data);
}
char *aero::get_destination()
{
    return destination;
}
 
void aero::set_numberofplane(char *data, int data1)
{
    //delete numberofplane;
    numberofplane = new char[data1];
    strcpy(numberofplane, data);
}
char *aero::get_numberofplane()
{
    return numberofplane;
}
 
void aero::set_typeofplane(char *data, int data1)
{
    //delete typeofplane;
    typeofplane = new char[data1];
    strcpy(typeofplane, data);
}
char *aero::get_typeofplane()
{
    return typeofplane;
}
 
void aero::set_departure(float data)
{
    departure = data;
}
float aero::get_departure()
{
    return departure;
}
 
void aero::dialogue(aero defaultAero, aero *plane, char *new_destination, char *new_numberofplane, char *new_typeofplane, float new_departure)
{
    cout << "Your DEFAULT plane is: ";
    //defaultAero.print();
    cout << endl;
    cout << "Write destination: ";
    cin >> new_destination;
    int size_new_destination = strlen(new_destination);
    cout << "Write number of plane: ";
    cin >> new_numberofplane;
    int size_new_numberofplaine = strlen(new_numberofplane);
    cout << "Write type of plane: ";
    cin >> new_typeofplane;
    int size_new_typeofplane = strlen(new_typeofplane);
    cout << "Write departure: ";
    cin >> new_departure;
    plane->set_destination(new_destination, size_new_destination);
    plane->set_numberofplane(new_numberofplane, size_new_numberofplaine);
    plane->set_typeofplane(new_typeofplane, size_new_typeofplane);
    plane->set_departure(new_departure);
    cout << "\nYour next plane is:";
}
void aero::print()
{
    cout << "\n" << destination << " " << numberofplane << " " << typeofplane << " " << departure << endl;
}

main.cpp
Кликните здесь для просмотра всего текста
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
#define _CRT_SECURE_NO_WARNINGS
#include "aero.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <time.h>
using namespace std;
const int N = 11;
 
void getaerodestination(aero *arr, char* new_destination);
void getaerotype(aero *arr, char *new_type);
void getaerodeparture(aero *arr, float new_departure);
int main()
{
srand(time(0));
    aero arr[N];
    char *a1 = "Kiev";          int size_a1 = strlen(a1) + 1;    char *b1 = "N395RC";   int size_b1 = strlen(b1) + 1;   float d1 = 20.02;
    char *a2 = "Munhen";        int size_a2 = strlen(a2) + 1;    char *b2 = "N53KJ";    int size_b2 = strlen(b2) + 1;   float d2 = 02.55;
    char *a3 = "Drezden";       int size_a3 = strlen(a3) + 1;    char *b3 = "URF12";    int size_b3 = strlen(b3) + 1;   float d3 = 15.45;
    char *a4 = "Vena";          int size_a4 = strlen(a4) + 1;    char *b4 = "URF16";    int size_b4 = strlen(b4) + 1;   float d4 = 08.15;
    char *a5 = "Berlin";        int size_a5 = strlen(a5) + 1;    char *b5 = "N800UP";   int size_b5 = strlen(b5) + 1;   float d5 = 14.38;
    char *a6 = "New_Jersy";     int size_a6 = strlen(a6) + 1;    char *b6 = "URF44";    int size_b6 = strlen(b6) + 1;   float d6 = 07.45;
    char *a7 = "Sydney";        int size_a7 = strlen(a7) + 1;    char *b7 = "N1165U";   int size_b7 = strlen(b7) + 1;   float d7 = 12.36;
    char *a8 = "Los_Angeles";   int size_a8 = strlen(a8) + 1;    char *b8 = "N530HP";   int size_b8 = strlen(b8) + 1;   float d8 = 16.58;
    char *a9 = "Vankyver";      int size_a9 = strlen(a9) + 1;    char *b9 = "N735JK";   int size_b9 = strlen(b9) + 1;   float d9 = 22.35;
    char *a0 = "Toronto";       int size_a0 = strlen(a0) + 1;    char *b0 = "URF14";    int size_b0 = strlen(b0) + 1;   float d0 = 10.15;
 
    
 
    char *c1 = "Passanger";     int size_c1 = strlen(c1) + 1;
    char *c2 = "Transporter";   int size_c2 = strlen(c2) + 1;
    char *c3 = "Military";      int size_c3 = strlen(c3) + 1;
 
    
    
    
 
    for (int i = 0; i < 10; i++)
    {
        int dest_count = rand() % 10;
        switch (dest_count)
        {
        case 0:
            arr[i].set_destination(a1, size_a1);
            break;
        case 1:
            arr[i].set_destination(a2, size_a2);
            break;
        case 2:
            arr[i].set_destination(a3, size_a3);
            break;
        case 3:
            arr[i].set_destination(a4, size_a4);
            break;
        case 4:
            arr[i].set_destination(a5, size_a5);
            break;
        case 5:
            arr[i].set_destination(a6, size_a6);
            break;
        case 6:
            arr[i].set_destination(a7, size_a7);
            break;
        case 7:
            arr[i].set_destination(a8, size_a8);
            break;
        case 8:
            arr[i].set_destination(a9, size_a9);
            break;
        case 9:
            arr[i].set_destination(a0, size_a0);
            break;
        }
 
        int numOFplane_count = rand() % 10;
        switch (numOFplane_count)
        {
        case 0:
            arr[i].set_numberofplane(b1, size_b1);
            break;
        case 1:
            arr[i].set_numberofplane(b2, size_b2);
            break;
        case 2:
            arr[i].set_numberofplane(b3, size_b3);
            break;
        case 3:
            arr[i].set_numberofplane(b4, size_b4);
            break;
        case 4:
            arr[i].set_numberofplane(b5, size_b5);
            break;
        case 5:
            arr[i].set_numberofplane(b6, size_b6);
            break;
        case 6:
            arr[i].set_numberofplane(b7, size_b7);
            break;
        case 7:
            arr[i].set_numberofplane(b8, size_b8);
            break;
        case 8:
            arr[i].set_numberofplane(b9, size_b9);
            break;
        case 9:
            arr[i].set_numberofplane(b0, size_b0);
            break;
        }
 
        int type_count = rand() % 3;
        switch (type_count)
        {
        case 0:
            arr[i].set_typeofplane(c1, size_c1);
            break;
        case 1:
            arr[i].set_typeofplane(c2, size_c2);
            break;
        case 2:
            arr[i].set_typeofplane(c3, size_c3);
            break;
        }
 
        int depart_count = rand() % 10;
        switch (depart_count)
        {
        case 0:
            arr[i].set_departure(d1);
            break;
        case 1:
            arr[i].set_departure(d2);
            break;
        case 2:
            arr[i].set_departure(d3);
            break;
        case 3:
            arr[i].set_departure(d4);
            break;
        case 4:
            arr[i].set_departure(d5);
            break;
        case 5:
            arr[i].set_departure(d6);
            break;
        case 6:
            arr[i].set_departure(d7);
            break;
        case 7:
            arr[i].set_departure(d8);
            break;
        case 8:
            arr[i].set_departure(d9);
            break;
        case 9:
            arr[i].set_departure(d0);
            break;
        }
        arr[i].print();
    }
 
    char *new_destination;
    cin >> new_destination;
 
    char *new_type;
    cin >> new_type;
 
    float new_departure;
    cin >> new_departure;
 
    getaerodestination(arr,new_destination);
    getaerodeparture(arr, new_departure);
    getaerotype(arr, new_type);
    
    _getch();
    return 0;
}
 
void getaerodestination(aero *arr, char *new_destination)
{
    for (int i = 0; i < 10; i++)
    {
        if (arr[i].get_destination == new_destination)
        {
            arr[i].print();
        }
        cout << "\n" << endl;
    }
}
 
void getaerodeparture(aero *arr, char *new_type)
{
    for (int i = 0; i < 10; i++)
    {
        if (arr[i].get_destination == new_type)
        {
            cout << arr[i].get_typeofplane;
        }
        cout << "\n" << endl;
    }
}
 
void getaerotype(aero *arr, float new_departure)
{
    for (int i = 0; i < 10; i++)
    {
        if (arr[i].get_departure > new_departure)
        {
            arr[i].print;
        }
        cout << "\n" << endl;
    }
}



В трех ф-ях getaerodestination, getaerodeparture, getaerotype нужно вывести все рейсы к заданному пункту назначения, вывести типы самолетов по заданному пункту назначения и вывести все самолеты время прибытия которых позже заданного соответственно к каждой функции.


В этих строках :
C++
1
2
3
if (arr[i].get_destination == new_destination)
if (arr[i].get_destination == new_type)
if (arr[i].get_departure == new_departure)
Выводит вот такие ошибки :
C++
1
2
3
4
5
6
Error   14  error C2040: '==' : 'char *(__thiscall aero::* )(void)' differs in levels of indirection from 'char *'
Error   21  error C2040: '==' : 'char *(__thiscall aero::* )(void)' differs in levels of indirection from 'char *'
Error   17  error C2296: '>' : illegal, left operand has type 'float (__thiscall aero::* )(void)
Error   13  error C2446: '==' : no conversion from 'char *' to 'char *(__thiscall aero::* )(void)'
Error   20  error C2446: '==' : no conversion from 'char *' to 'char *(__thiscall aero::* )(void)'
Error   16  error C2446: '>' : no conversion from 'float' to 'float (__thiscall aero::* )(void)'
Ничего не могу понять, вроде char* с char* все правильно; потом, зачем-то конвертация с float в float пишет как ошибку.
Что посоветуете, какие замечания будут?

P.S. Как можно еще задать вот это все:
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
char *a1 = "Kiev"; int size_a1 = strlen(a1) + 1;
char *b1 = "N395RC"; int size_b1 = strlen(b1) + 1;
char *a2 = "Munhen"; int size_a2 = strlen(a2) + 1;
char *b2 = "N53KJ"; int size_b2 = strlen(b2) + 1;   
.
.
.


Только в нормальном, человеческом виде ?
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
05.10.2014, 15:18
Ответы с готовыми решениями:

[Selenium] Поиск кнопки по классу class="_ah57t _84y62 _i46jh _rmr7s"
Доброе время суток! Делаю чекер для instagram. но для этого нужно авторизоваться, с помощью selenium делаю ввод логина и пароля, далее хочу...

Подскажите ссылку к классу для работы с файлами /типа class CFiles в MFC /
Можно конечно и самому написать, но не хочется изобретать велосипед.

Освобождение памяти (удаление массива char) и raised exception class EAccessViolation
Подскажите плиз, есть программа, вот кусок AnsiString inputText; int inputTextLength; inputText= Form1-&gt;Edit1-&gt;Text; ...

2
БНТУ ФИТР
 Аватар для kventin_zhuk
215 / 155 / 42
Регистрация: 26.12.2012
Сообщений: 382
05.10.2014, 15:31
iga7013, как-то стремно вы вызываете метод класса

C++
1
arr[i].get_destination
нужно вот так
C++
1
arr[i].get_destination()
и массивы чаров не сравниваются с помощью операторов сравнения

для этого есть спец функции

http://www.cplusplus.com/reference/cstring/
0
1 / 1 / 0
Регистрация: 02.06.2013
Сообщений: 38
05.10.2014, 19:22  [ТС]
Да, верно, пропустил такой момент. Исправил и заработало.

Использовал для сравнения strcmp(char*, char*) == 0

Спасибо!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
05.10.2014, 19:22
Помогаю со студенческими работами здесь

Записать в текстовый файл массив обьектов с полями разных типов
Записать в текстовый файл массив обьектов с полями разных типов, и потом считать из файла данные и записать в массив по типу идентичному из...

Отправка char классу
Всем привет Вот так вот пытаюсь отправить buff на обработку классу APPA_codes /* Пусть будет main.cpp */ char buff; //в...

Поиск из "Массива обьектов класса" по свойствам(имени, дате.)
Всем доброго времени суток. Есть проблема такая, мне нужно например вывести из массива обьектов класса определенного человека по имени...

Быстрая сортировка для массива обьектов пользовательского класса
Насколько я знаю в Си++ есть встроеная ф-ция быстрой сортировки. Как нею воспользоваться для сортировки массива обьектов моего класса? Хочу...

Поиск максимального элемента массива char
В чем моя ошибка, подскажите, пожалуйста? template&lt;&gt; char* Max&lt;char*&gt;(char **&amp;arr, int &amp;size) { char *max = 0; for (int i = 0;...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Кому нужен AOT?
DevAlt 26.03.2026
Решил сделать простой ланчер Написал заготовку: dotnet new console --aot -o UrlHandler var items = args. Split(":"); var tag = items; var id = items; var executable = args;. . .
Отправка уведомления на почту при изменении наименования справочника
Maks 24.03.2026
Программная отправка письма электронной почты на примере изменения наименования типового справочника "Склады" в конфигурации БП3. Перед реализацией необходимо выполнить настройку системной учетной. . .
модель ЗдравоСохранения 5. Меньше увольнений- больше дохода!
anaschu 24.03.2026
Теперь система здравосохранения уменьшает количество увольнений. 9TO2GP2bpX4 a42b81fb172ffc12ca589c7898261ccb/ https:/ / rutube. ru/ video/ a42b81fb172ffc12ca589c7898261ccb/ Слева синяя линия -. . .
Midnight Chicago Blues
kumehtar 24.03.2026
Такой Midnight Chicago Blues, знаешь?. . Когда вечерние улицы становятся ночными, а ты не можешь уснуть. Ты идёшь в любимый старый бар, и бармен наливает тебе виски. Ты смотришь на пролетающие. . .
SDL3 для Desktop (MinGW): Вывод текста со шрифтом TTF с помощью библиотеки SDL3_ttf на Си и C++
8Observer8 24.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-text-sdl3-c. zip finish-text-sdl3-cpp. zip
Жизнь в неопределённости
kumehtar 23.03.2026
Жизнь — это постоянное существование в неопределённости. Например, даже если у тебя есть список дел, невозможно дойти до точки, где всё окончательно завершено и больше ничего не осталось. В принципе,. . .
Модель здравоСохранения: работники работают быстрее после её введения.
anaschu 23.03.2026
geJalZw1fLo Корпорация до введения программа здравоохранения имела много невыполненных работниками заданий, после введения программы количество заданий выросло. Но на выплатах по больничным это. . .
Контроль уникальности заводского номера
Maks 23.03.2026
Алгоритм контроля уникальности заводского (или серийного) номера на примере нетипового документа выдачи шин для спецтехники с табличной частью, разработанного в конфигурации КА2. Номеклатура. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru