gpt4 book ai didi

c++ - 为什么我的 C++ 代码出现 "undeclared identifier"错误?

转载 作者:行者123 更新时间:2023-11-28 04:03:41 26 4
gpt4 key购买 nike

因此,我们在学校被分配安排上课时间。他们希望我们用一个 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;
}

主要.cpp

#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,我将 header 到 mytime.h 和 time 类到 mytime。一旦消除了歧义的可能性,所有错误都会消失(一些关于未使用参数的警告仍然存在)。

我建议使用比 mytime 稍微平淡一些的名称,但只要名称具有描述性且不会发生冲突,您可以随意使用任何名称。

关于c++ - 为什么我的 C++ 代码出现 "undeclared identifier"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com