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

как разбить cpp файл на cpp и h

09.12.2021, 00:13. Показов 406. Ответов 1
Метки c++ (Все метки)

Студворк — интернет-сервис помощи студентам
Доброй ночи, необходимо разбить файл на cpp и h.
Если я в cpp файле я оставляю int main(){***}, а остальное перенjшу в .h, то программа перестает работать. Хотя содержимое файла .h должно копироваться в 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
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
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<iomanip>
 
#include <stack>
#include <vector>
 
 
using namespace std;
int score=0;
int undo_limit=0;
int undo_score=0;
class play{
    stack<vector<vector<int> > > undo_stack;
    stack<int> score_stack;
 
 
    int g[4][4];
    int g_copy[4][4];
    void initialize();
    void display();
    void move_up();
    void move_down();
    void move_left();
    void move_right();
    int check_full();
    int random_index(int x);
    void sum_up();
    void sum_down();
    void sum_left();
    void sum_right();
    void generate_new_index();
    int calculate_max();
    void instructions();
    int game_ends();
    void end_display();
    void win_display();
    void lose_display();
    void restart();
 
    public:
    void play_game();
    play(){
    }
};
 
void play :: instructions(){
    cout<<"\nInstructions for playing 2048 are:: \n"<<endl;
    cout<<"For moving tiles enter \n w-move up \n a-move left \n d-move right \n s-move down \n"<<endl;
    cout<<"When two tiles with same number touch, they merge into one. \nWhen 2048 is created, the player wins!\n"<<endl;
    // cout<<"please don't try to undo consecutively\n\n";
    cout << "maximum 5 undo operations are supported\n";
    display();
}
 
int play :: random_index(int x){
    int index;
    index=rand()%x + 0;
    return index;
}
 
void play :: lose_display(){
    system("clear");
    cout<<"\t\t\tGAME OVER\n\n";
    cout<<"Your final score is "<<score<<"\n\n";
    cout<<"Thanks for trying!!!\n\n";
    cout<<"\t\t\tA msdeep14 CREATION\n\n";
    exit(0);
}
 
void play :: restart(){
    char ch;
    cout<<"\nAre you sure to restart the game??\n\n";
    cout<<"enter y to restart and n to continue.\n\n";
    cin>>ch;
    if(ch=='y'){
        score=0;
        undo_score=0;
        undo_stack = stack<vector<vector<int> > >();
        score_stack = stack<int>();
        initialize();
    }
}
 
int play :: check_full(){
    int full_flag=1;
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            if(g[i][j]==0){
                full_flag=0;
                break;
            }
        }
    }
    return full_flag;
}
 
void play :: win_display(){
    char ch;
    cout<<"\t\t\tYOU WON!!!\n\n";
    cout<<"Your total score is "<<score<<"\n\n";
    cout<<"Do you wish to continue???\n";
    cout<<"Enter y to continue and n to quit\n\n";
    cin>>ch;
    if(ch=='n'){
        end_display();
    }
}
 
int play :: calculate_max(){
    int i,j;
    int max=0;
    for(i=0;i<4;i++){
        for(j=0;j<4;j++){
            if(g[i][j]>max){
                max=g[i][j];
            }
        }
    }
    return max;
}
 
void play :: end_display(){
    system("clear");
    cout<<"\nYour final score is :: "<<score<<endl<<endl;
    cout<<"Thanks for trying!!!\n\n";
    cout<<"Good Bye!!!\n"<<endl;
    cout<<"\t\t\tA msdeep14 CREATION\n\n";
    exit(0);
}
 
int play :: game_ends(){
    int i,j,flag=1;
    for(i=0;i<4;i++){
        for(j=0;j<3;j++){
            if(g[i][j]==g[i][j+1]){
                flag=0;
                break;
            }
        }
        if(flag==0){
                break;
        }
    }
    if(flag==1){
        for(i=0;i<3;i++){
            for(j=0;j<4;j++){
                if(g[i][j]==g[i+1][j]){
                    flag=0;
                    break;
                }
            }
            if(flag==0){
                break;
            }
        }
    }
    return flag;
}
 
 
void play :: generate_new_index(){
    int flag=1;
    if(!check_full()){
        while(flag){
            int i=random_index(4);
            int j=random_index(4);
            if(g[i][j]==0){
                int y=rand()%10+0;
                if(y<6){
                    g[i][j]=2;
                }else{
                    g[i][j]=4;
                }
                flag=0;
            }
        }
    }
}
 
/*
    * initialize the matrices g and g_copy
    * two of the indices to value = 2 and other values to 0
*/
void play :: initialize(){
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            g[i][j]=0;
            g_copy[i][j]=0;
        }
    }
    int i=random_index(4);
    int j=random_index(4);
    g[i][j]=2;
    i=random_index(4);
    j=random_index(4);
    g[i][j]=2;
    display();
}
 
 
void play :: move_up(){
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            if(!g[j][i]){
                for(int k=j+1;k<4;k++){
                    if(g[k][i]){
                        g[j][i]=g[k][i];
                        g[k][i]=0;
                        break;
                    }
                }
            }
        }
    }
}
 
void play :: move_down(){
    for(int i=0;i<4;i++){
        for(int j=3;j>=0;j--){
            if(!g[j][i]){
                for(int k=j-1;k>=0;k--){
                    if(g[k][i]){
                        g[j][i]=g[k][i];
                        g[k][i]=0;
                        break;
                    }
                }
            }
        }
    }
}
 
void play :: move_left(){
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            if(!g[i][j]){
                for(int k=j+1;k<4;k++){
                    if(g[i][k]){
                        g[i][j]=g[i][k];
                        g[i][k]=0;
                        break;
                    }
                }
            }
        }
    }
}
 
void play :: move_right(){
    for(int i=0;i<4;i++){
        for(int j=3;j>=0;j--){
            if(!g[i][j]){
                for(int k=j-1;k>=0;k--){
                    if(g[i][k]){
                        g[i][j]=g[i][k];
                        g[i][k]=0;
                        break;
                    }
                }
            }
        }
    }
}
 
void play :: sum_up(){
    for(int i=0;i<4;i++){
        for(int j=0;j<3;j++){
            if(g[j][i] && g[j][i]==g[j+1][i]){
                g[j][i]=g[j][i] + g[j+1][i];
                g[j+1][i]=0;
                score+=g[j][i];
                undo_score+=g[j][i];
            }
        }
    }
}
 
void play :: sum_down(){
    for(int i=0;i<4;i++){
        for(int j=3;j>0;j--){
            if(g[j][i] && g[j][i]==g[j-1][i]){
                g[j][i]=g[j][i] + g[j-1][i];
                g[j-1][i]=0;
                score+=g[j][i];
                undo_score+=g[j][i];
            }
        }
    }
}
 
void play :: sum_left(){
    for(int i=0;i<4;i++){
        for(int j=0;j<3;j++){
            if(g[i][j] && g[i][j]==g[i][j+1]){
                g[i][j]=g[i][j] + g[i][j+1];
                g[i][j+1]=0;
                score+=g[i][j];
                undo_score+=g[i][j];
            }
        }
    }
}
 
void play :: sum_right(){
    for(int i=0;i<4;i++){
        for(int j=3;j>0;j--){
            if(g[i][j] && g[i][j]==g[i][j-1]){
                g[i][j]=g[i][j] + g[i][j-1];
                g[i][j-1]=0;
                score=score + g[i][j];
                undo_score+=g[i][j];
            }
        }
    }
}
 
/*
    * function to take choice from user
    * and call functions accordingly
*/
void play :: play_game(){
    int flag=0;
    char choice,ch;
    initialize();
    cin>>choice;
 
    while((choice=='w' || choice=='a' || choice=='s' || choice=='d' || choice=='q' || choice=='i' || choice=='u' || choice=='r')){
        if(choice != 'u'){
            vector<vector <int> > current_copy;
            current_copy.resize(4);
            for(int m = 0;m<4; m++){
                for(int n=0; n<4; n++){
                    current_copy[m].push_back(g[m][n]);
                }
            }
            undo_stack.push(current_copy);
        }
 
        // if(choice!='u'){
        //  for(int m=0;m<4;m++){
        //      for(int n=0;n<4;n++){
        //          g_copy[m][n]=g[m][n];
        //      }
        //  }
        // }
 
    switch(choice){
        //move up
        case 'w':
            undo_score=0;
            move_up();
            sum_up();
            move_up();
            generate_new_index();
            system("clear");
            display();
            score_stack.push(undo_score);
            break;
        //move down
        case 's':
            undo_score=0;
            move_down();
            sum_down();
            move_down();
            generate_new_index();
            system("clear");
            display();
            score_stack.push(undo_score);
            break;
        //move left
        case 'a':
            undo_score=0;
            move_left();
            sum_left();
            move_left();
            generate_new_index();
            system("clear");
            display();
            score_stack.push(undo_score);
            break;
        //move right
        case 'd':
            undo_score=0;
            move_right();
            sum_right();
            move_right();
            generate_new_index();
            system("clear");
            display();
            score_stack.push(undo_score);
            break;
        //quit
        case 'q':
            cout<<"Are you sure you want to quit??\nEnter y to quit and n to continue!\n"<<endl;
            cin>>ch;
            if(ch=='y' || ch == 'Y'){
                end_display();
            }
            display();
            break;
        //display instructions
        case 'i':
            instructions();
            break;
        //restart 2048
        case 'r':
            restart();
            break;
        //undo move
        case 'u':
            if(undo_limit < 5){
                if(!undo_stack.empty()){
                    vector<vector<int> > previous_copy = undo_stack.top();
                    undo_stack.pop();
                    for(int m=0;m<4;m++){
                        for(int n=0;n<4;n++){
                            g[m][n]=previous_copy[m][n];
                        }
                    }
                    // score -= undo_score;
                    score -= score_stack.top();
                    score_stack.pop();
                    undo_limit += 1;
                }else{
                    system("clear");
                    cout << "\n\nundo not POSSIBLE, reached initial state!!!\n\n";
                    display();
                }
            }else{
                system("clear");
                display();
                cout<<"\n\nYou cannot undo the matrix more than 5 times.\n\nSorry!!!\n"<<endl;
            }
    }
    //check if any block of matrix reached to value = 2048
    int find_max=calculate_max();
    if(find_max==2048){
        win_display();
    }
    /*
        * check_full() checks if grid is full
        * game_ends() perform a check if continuous block in up-down or
          right-left direction has same values
        * if no continuous block has same value, then no further move can be made
          and game ends
    */
        if(check_full()){
            if(game_ends()){
                lose_display();
            }
        }
        cout<<"enter choice: "<<endl;
        cin>>choice;
        while(choice!='w'  && choice!='s'  && choice!='d'  && choice!='a' && choice!='q' && choice!='i' && choice!='u' && choice!='r'){
            cout<<"\nYou had entered the wrong choice!\nPlease enter correct choice to continue!"<<endl;
            cin>>choice;
        }
    }
}
 
/*
    * display function
    * called after every move
*/
void play :: display(){
    cout<<"\n\t\t\t\t\t\t\t 2048\n\n";
    cout<<"\t\t\t\t\t\t  A msdeep14 CREATION\n\n";
    cout<<"  score :: "<<score<<endl<<endl;
    for(int i=0;i<4;i++){
        cout<<"                       ";
        for(int j=0;j<4;j++){
            cout<<setw(8)<<g[i][j]<<setw(8)<<"|"<<setw(8);
        }
        cout<<endl<<endl<<endl;
    }
    cout<<"\n\n\n";
 
//  cout<<"\t\t\t\t\t\t\t\t\tr-restart\n\tw\t\t\t\t^\t\t\t\ti-instructions\na\ts\td\t\t<\t"<<"v"<<"\t>\t\t\tq-quit  u-undo\n\n";
    cout<<"\t\t\t\t\t\t\t\t\tr-restart\n\tw\t\t\t\t\t\t\t\ti-instructions\na\ts\td\t\t\t\t\t\t\tq-quit  u-undo\n\n";
}
 
int main(){
    play p;
    srand(time(NULL));
    p.play_game();
    return 0;
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
09.12.2021, 00:13
Ответы с готовыми решениями:

Есть три файла. файл main.cpp и Source.cpp знают только Header.h, так как он подключен. как же подключается Source.cpp
main.cpp #include &lt;iostream&gt; #include&quot;Header.h&quot; using namespace std; int main() { A ob; ob.f(); return...

Как разбить код на несколько *.CPP*
Как разбить код на несколько *.CPP* Добрый вечер - при изучении языка С где то в литературе видемо упустил такую информацию и не где...

С помощью командной строки >namberstr f1.cpp Определить число строк в файле с именем f1.cpp
С помощью командной строки &gt;namberstr f1.cpp Определить число строк в файле с именем f1.cpp

1
7804 / 6568 / 2988
Регистрация: 14.04.2014
Сообщений: 28,705
09.12.2021, 00:43
В h переносишь класс, в cpp - реализацию. А main остаётся в своём cpp.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
09.12.2021, 00:43
Помогаю со студенческими работами здесь

Включение библиотек в main.cpp и my_func.cpp
Здравствуйте, Подскажите пожалуйста, ни как не могу понять, вот если: //main.cpp #include &lt;iostream&gt; int main() ...

Подключение файлов main.cpp some.cpp some.h
Всем привет, программа разделенна на три файла poly.cpp main.cpp poly.h Кто мог бы объяснить как происходит подключение этих файлов, и как...

Библиотеки в CPP. Ошибка компиляции | CPP
Доброго вечера! Появился один вопросик недавно. Начал юзать библиотеку &lt;windows.h&gt; для использования такой команды как...

Разбить на два файла .h и .cpp
Ребят, подскажите, как правильно разбить эту программу на два файла .h и .cpp #include &lt;math.h&gt; #include &lt;iostream&gt; ...

Разбить main.cpp на файлы
Есть вот такой main.cpp: #include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;string.h&gt; //#include &lt;stdint.h&gt; //#include...


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

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и напряжениями. Надо найти токи в ветвях. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и решает её. Последовательность действий:. . .
Новый CodeBlocs. Версия 25.03
palva 04.01.2026
Оказывается, недавно вышла новая версия CodeBlocks за номером 25. 03. Когда-то давно я возился с только что вышедшей тогда версией 20. 03. С тех пор я давно снёс всё с компьютера и забыл. Теперь. . .
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru