[英]Why am i getting an "undeclared identifier" error in my c++ code?
所以我们在学校被分配创建一个上课时间。 他们希望我们用 time.h 头文件、time.cpp cpp 文件和 main.cpp cpp 文件将类分开。 我有以下代码,但由于某种原因,我不断收到“未声明的标识符”错误。 所有 3 个文件现在都包含在我的项目中。
这是代码:
时间.h
class time
{
private:
int hours;
int minutes;
int seconds;
public:
time();
time(int sec);
time(int h, int min, int sec);
int getTime();
void setHours(int h);
void setMinutes(int min);
void setSeconds(int sec);
bool equals(time t);
void addTime(time t);
void printTime();
void normalize();
};
时间.cpp
#include "time.h"
#include <iostream>
#include <iomanip>
using namespace std;
time::time()
{}
time::time(int sec)
{}
time::time(int h, int min, int sec)
{}
int time::getTime()
{
return (hours * 60 * 60) + (minutes * 60) + seconds;
}
void time::setHours(int h)
{
hours = h;
}
void time::setMinutes(int min)
{
minutes = min;
}
void time::setSeconds(int sec)
{
seconds = sec;
}
bool time::equals(time t)
{
if (hours == t.hours && minutes == t.minutes && seconds == t.seconds)
return true;
else return false;
}
void time::addTime(time t)
{
hours += t.hours;
minutes += t.minutes;
seconds += t.seconds;
}
void time::printTime()
{
cout << setfill('0') << setw(2) << hours
<< ":" << setfill('0') << setw(2) << minutes
<< ":" << setfill('0') << setw(2) << seconds;
}
void time::normalize()
{
seconds %= 60;
minutes = minutes + (seconds / 60);
hours = hours + (minutes / 60);
minutes = minutes % 60;
}
主程序
#include "time.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
time time1;
int seconds1;
cout << "Enter the amount of seconds: ";
cin >> seconds1;
time time2(seconds1);
int hours2, minutes2, seconds2;
cout << "Enter the amount of hours: ";
cin >> hours2;
cout << "Enter the amount of muinutes: ";
cin >> minutes2;
cout << "Enter the amount of seconds: ";
cin >> seconds2;
time time3(hours2, minutes2, seconds2);
time1.equals(time2);
}
编译给定的代码,我收到了一大堆错误消息,最能说明问题的是
warning: statement is a reference, not call, to function 'time' time time1; ^
这导致time1
被报告为未稍后声明,因为它不是。
标准库包含头文件 time.h 和函数time.
为确保程序包含正确的 time.h 并使用正确的time
,我将标题重命名为 mytime.h,将time
类重命名为mytime
。 一旦消除了歧义的可能性,所有错误就会消失(一些关于未使用参数的警告仍然存在)。
我建议使用比mytime
稍微平庸一点的mytime
,但是只要名称是描述性的并且没有更多的冲突,就可以随意使用任何你想要的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.