在函数下调用函数时找不到标识符

Identifier not found when calling a function under a function

本文关键字:函数 找不到 标识符 调用      更新时间:2024-09-23

我试图开发一个同时显示12小时和24小时时钟的程序。但每当我编译时,我都会收到一个生成错误,上面写着"GetAM_PM":找不到标识符。尽管在函数参数中使用了相同的变量,但在第26行我还是得到了这个错误。这个问题的根源可能是什么?这是我的代码:

#include <iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
//converting it into 12 hour format
int TwelveHourFormat(int twelve_hours) {
return (twelve_hours == 0 || twelve_hours == 12) ? 12 : 
twelve_hours % 12;
}

//printing the 12 hour format
void Display_12_HourFormat(int seconds, int minutes, int 
twelve_hours) {
cout.fill('0');
cout << TwelveHourFormat(twelve_hours) << ":" << minutes << ":" 
<< seconds << " " << GetAM_PM(twelve_hours);
}
//printing the 24 hour format
void Display_24_HourFormat(int seconds, int minutes, int 
twenty_four_hours) {
cout.fill('0');
cout << twenty_four_hours << ":" << minutes << ":" << seconds;
}

void AddHour(int hour) {
hour = (hour + 1) % 24;
}

void AddMinute(int hour, int min) {
if (min == 59) {
AddHour(hour);
}
min = (min + 1) % 60;
}
void AddSecond(int min, int sec) {
if (sec == 59) {
AddMinute(min, sec);
}
sec = (sec + 1) % 60;
}
// function return AM/PM respect to hour of time
string GetAM_PM(int twelve_hours) {
return twelve_hours >= 12 ? "PM" : "AM";
}

// This method prints the menu options
void DisplayMenu() {
cout << "Chada Tech Clocks Menu" << endl;
cout << "[1] Add one hour" << endl;
cout << "[2] Add one minute" << endl;
cout << "[3] Add one second" << endl;
cout << "[4] Exit program" << endl;
}
int main()
{  
int seconds, minutes, hours;
//obtains current time in seconds
time_t total_seconds = time(0); 
//getting values of seconds, minutes and hours
struct tm ct;
localtime_s(&ct, &total_seconds);
seconds = ct.tm_sec;
minutes = ct.tm_min;
hours = ct.tm_hour;
// Variable declared
int option;
do
{
// DisplayMenu function is called
DisplayMenu();

cin >> option;
// If user input is 1, Clock function is called
if (option == 1) {
TwelveHourFormat(hours);
AddHour(hours);
GetAM_PM(hours);
Display_12_HourFormat(seconds, minutes, hours);
Display_24_HourFormat(seconds, minutes, hours);

}
// If the option is 2, the Clock function is called
else if (option == 2) {
AddMinute(minutes, seconds);
GetAM_PM(hours);
}
// If the option is 3, the Clock function is called
else if (option == 3) {
AddSecond(minutes, seconds);
GetAM_PM(hours);

}
// If the option is 4, exit message prints and application 
stops running
else if (option == 4) {
cout << "You have exited the application.";
break;
}
else {
cout << "You have entered an invalid input." << endl;
}
} while (option != 4);
}

在定义Display_12_HourFormat之前,需要声明GetAM_PM。否则,编译器在解析调用GetAM_PMDisplay_12_HourFormat函数时将不知道它。

只需将这些行移到开头,在任何其他函数之前:

// function return AM/PM respect to hour of time
string GetAM_PM(int twelve_hours) {
return twelve_hours >= 12 ? "PM" : "AM";
}

事实并非如此,但如果最终出现循环依赖,请尝试在.h中声明方法,或在代码中转发声明方法。