c++ - 在我的 cpp 或头文件中找不到错误,类构造失败

标签 c++ visual-studio class

<分区>

首先,我是 C++ 的新手,只有很少的教学/实践,所以请记住这一点。我为我正在处理的项目创建了一个 Date 类。我以前以一种草率的方式组织我的代码,但它的功能足以让我有效地编写我的代码的语法。在有人查看我的代码后,我意识到我需要更好地构建我的类,因此尝试将我的 Date 类组织到一个头文件和 cpp 文件中。这样做之后,我得到了一些错误:

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

此外,Date 在 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 

日期.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 守卫。

那是因为 #include 通过复制粘贴整个头文件来工作。并且因为您在包含 Date.h header 之前定义了 DATE_H,所以 DATE_H 也在 Date.h 中定义(然后有效地禁用了 entre header )。

关于c++ - 在我的 cpp 或头文件中找不到错误,类构造失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096804/

相关文章:

c++ - 模板类,友元运算符 << 重载

c++ - 错误 : no matching function for call to

c++ - QXmlStreamReader获取标签值

c++ - 在 Mac 上检测 PDF 打印

c - 在 C 中使用 `this` 关键字是否明智?

c++ - 将对象数组、对象的数量和所需的术语传递给函数

c++ - 从 Qt 5.7 升级到 5.10 导致 UI 变慢

c++ - 在 VM 中调试进程

mysql dll 永远不会出现在 bin 文件夹中

visual-studio - 在VS2005/2008中自动化 "Attach to Process"