在我的 cpp 或头文件中找不到错误,类构建失败

Can't find the error in my cpp or header file, class construction failing

本文关键字:错误 构建 失败 找不到 cpp 我的 文件      更新时间:2023-10-16

首先,我是C 的新手,只有最少的教学/实践,因此请记住这一点。我为正在从事的项目创建了一个日期课程。我以前曾以草率的方式组织了我的代码,但是它功能足以使我有效地编写代码的语法。有人查看了我的代码后,我意识到我需要更好地构建课程,因此尝试将日期课程组织到标题和CPP文件中。这样做之后,我沿着以下路线遇到了许多错误:

'day': undeclared identifier
missing type specifier - int is assumed

另外,日期被认为是CPP文件中的类型,因为它会在Visual Studio中更改颜色,但是在标题文件中,该类并未将其颜色为类型。

一位导师浏览了我的错误来自何处,但是如果我删除这两个文件,我的代码函数没有错误,因此在下面的脚本中肯定是某个地方。

我已经尝试从头开始重建整个项目,因为我最初认为这是一个目录问题,但是精心完成此操作并完全确定我没有放错了文件,我看不出它会如何因此。

date.h

#pragma once
#ifndef DATE_H
#define DATE_H
class Date
{
public:
    Date(int y, int m, int d);
    Date();
    const int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int yearsDifference();
    int daysDifference();
    int totalDays();
private:
    int year;
    int month;
    int day;
};
#endif 

date.cpp

#ifndef DATE_H
#define DATE_H
#include <Date.h>
#include <iostream>
#include <string>

Date::Date(int y, int m, int d)
{
    y = year;
    m = month;
    d = day;
}
Date::Date()
{
    year = 0;
    month = 0;
    day = 0;
}
static Date today() {
    struct tm ti;
    time_t t = time(0);
    localtime_s(&ti, &t);
    int y = 1900 + ti.tm_year;
    int m = 1 + ti.tm_mon;
    int d = ti.tm_mday;
    return Date(y, m, d);
}

int Date::yearsDifference()
{
    bool laterInYear = (month > today().month)
        || (month == today().month && day > today().day);
    int result = year - today().year;
    if (!laterInYear)
    {
        result--;
    }
    return result;
}

int Date::daysDifference()
{
    int todayMonthDays = 0;
    int maturityMonthDays = 0;
    for (int i = 0; i < (month - 1); i++) {
        maturityMonthDays += monthDays[i];
    }

    for (int i = 0; i < (today().month - 1); i++) {
        todayMonthDays += monthDays[i];
    }
    maturityMonthDays += day;
    todayMonthDays += today().day;
    bool laterInYear = (month > today().month)
        || (month == today().month && day > today().day);
    int result;
    if (laterInYear)
    {
        result = maturityMonthDays - todayMonthDays;
    }
    else
    {
        result = 365 - (todayMonthDays - maturityMonthDays);
    }
    return result;
}
int Date::totalDays()
{
    int result = (yearsDifference() * 365)
        + daysDifference();
    return result;
}
#endif

任何帮助都将不胜感激,我一直在盯着这个数小时试图修复它,而我只是看不到它。

您必须在.cpp文件中删除 #ifdef Guard。

这是因为#include通过复制N-Paster the整个标头文件来工作。并且由于您在包含date.h头之前定义date_h,因此在date.h中也定义了date_h(然后有效地禁用enitre header(。

数据类构造函数应该像这样

Date::Date(int y, int m, int d):
    year(y),
    month(m),
    day(d)
{}

还删除cpp文件中的ifdef