【问题标题】:Why am i getting an "undeclared identifier" error in my c++ code?为什么我的 C++ 代码中出现“未声明的标识符”错误?
【发布时间】:2019-11-28 19:47:24
【问题描述】:

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

main.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);

}

【问题讨论】:

  • 请包含完整的错误信息。
  • 你是怎么编译的?
  • 哪个标识符?

标签: c++ class undeclared-identifier


【解决方案1】:

编译给定的代码我收到一大堆错误消息,最能说明问题的是

warning: statement is a reference, not call, to function 'time'
     time time1;
          ^

这导致time1 被报告为稍后未声明,因为它不是。

标准库包含头文件 time.h 和函数 time. 为确保程序包含正确的 time.h 并使用正确的 time,我将头文件重命名为 mytime.h 和 time 类到mytime。一旦消除了歧义的可能性,所有错误都消失了(关于未使用参数的一些警告仍然存在)。

我建议使用比mytime 更简单的名称,但只要名称具有描述性并且没有更多冲突,您可以随意使用。

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多