我正在嘗試創建一個簡單的文本冒險,並且將代碼拆分爲多個頭文件,以使編譯時間更快並使其更加有組織。在C++中,如何引用不同頭文件中的函數?
//main.cpp
#include <iostream>
#include <fstream>
#include "main_menu.h"
#include "file_select.h"
using namespace std;
int main()
{
main_menu();
}
主菜單頭文件看起來是這樣的:
\\main_menu.h
#ifndef main_menu_H
#define main_menu_H
#include <iostream>
#include "file_select.h"
using namespace std;
void main_menu() {
cout << string(50,'\n');
cout << " ADVENTURE OF THE SKYLANDS \n";
cout << "================================================================================\n";
cout << " CHAPTER 1 \n";
cout << "================================================================================\n";
cout << " Scepter of The Winds \n";
cout << " v1.0.0 \n";
cout << "================================================================================\n";
char select;
cout << "\n\n\n\n\n" << "MAIN MENU\n\n";
cout << "1. Start\n";
cout << "2. File Select\n";
cout << "3. Credits\n";
cout << "4. Exit Game\n";
cin >> select;
if (select == 'S' || select == 's' || select == '1') {
}
else if (select == 'F' || select == 'f' || select == '2') {
file_select();
}
else if (select == 'C' || select == 'c' || select == '3') {
}
else if (select == 'E' || select == 'e' || select == 'x' || select == 'X' || select == '4') {
return;
}
else {
cout << "Invalid Option!";
}
}
#endif
#include
最後,文件選擇菜單的頭文件,這就是我有一個錯誤:「MAIN_MENU」並沒有在此聲明範圍。
#ifndef file_select_H
#define file_select_H
#include <iostream>
#include "main_menu.h"
using namespace std;
void file_select() {
cout << " FILE SELECT \n";
cout << "==================================================================================\n";
cout << "1. File 1\n";
cout << "2. File 2\n";
cout << "3. File 3\n";
cout << "4. Return to Main Menu\n";
char fileselect;
cin >> fileselect;
if (fileselect == '1') {
}
else if (fileselect == '2') {
}
else if (fileselect == '3') {
}
else if (fileselect == '4') {
main_menu();
}
else {
cout << "Invalid Option.";
}
}
#endif
不要把功能*定義*在頭文件(除非你聲明爲'static'或'inline')。相反,將定義放在單獨的源文件中,並且只將*聲明*放在頭文件中。 –
你的問題是什麼?你的代碼還有什麼其他問題? –
我該如何解決我的代碼問題,以便它能正常工作?就像我如何引用一個函數讓我們說Header1.h並且想在Header2.h中提及它吧。 –