我对编程还是很陌生,遇到了一个我确信是非常基础的问题。
所以我想做的是使用我在一个 .h 文件中定义的函数,然后在属于该 .h 文件的 .cpp 文件中写出到另一个 .cpp 文件中。这可能吗?
Date.h文件:
#pragma once
#ifndef DATE_GUARD
#define DATE_GUARD
#include <iostream>
class Date
{
public:
Date();
Date(int);
int getDay();
int getMonth();
int getYear();
int getDate();
bool leapYear();
~Date();
private:
int theDate;
};
#endif
CPR.h文件
#pragma once
#include"Date.h"
class CPR
{
public:
CPR();
CPR(unsigned long); //DDMMYYXXXX
Date getDate();
int getFinalFour();
bool validate();
int getFirstCipher();
int getSecondCipher();
int getThirdCipher();
int getFourthCipher();
int getFifthCipher();
int getSixthCipher();
int getSeventhCipher();
int getEighthCipher();
int getNinthCipher();
int getTenthCipher();
~CPR();
private:
int CPRNummer;
Date birthday;
};
Date.cpp文件
#include "Date.h"
Date::Date()
{
}
Date::Date(int aDate)
{
theDate = aDate;
}
int Date::getDay()
{
return theDate / 10000;
}
int Date::getMonth()
{
return (theDate / 100) % 100;
}
int Date::getYear()
{
return (theDate % 100);
}
bool Date::leapYear()
{
if (getYear() % 4 != 0)
return false;
if (getYear() % 100 == 0 && getYear() % 400 != 0)
return false;
return true;
}
int Date::getDate()
{
return theDate;
}
Date::~Date()
{
}
CPR.cpp文件(仅重要部分)
#include "CPR.h"
#include "Date.h"
#include <iostream>
bool CPR::validate()
{
if (getDay() < 1 || getDay() > 31)
return false;
if (getMonth() < 1 || getMonth() > 12)
return false;
if (getYear() < 1700 || getYear() > 2100)
return false;
if (getMonth() == 2 && leapYear() && getDay() > 29)
return false;
if (!leapYear() && getMonth() == 2 && getDay() > 28 || getMonth() == 4 && getDay() > 30 || getMonth() == 6 && getDay() > 30 || getMonth() == 9 && getDay() > 30 || getMonth() == 11 && getDay() > 30)
return false;
return true;
}
所以我尝试在 CPR.cpp 中使用 Date.cpp 中的 leapYear()、getMonth()、getDay() 和 getYear() 函数。
最佳答案
试试这个。但是你的程序似乎仍然不正确:
bool CPR::validate()
{
if (birthday.getDay() < 1 || birthday.getDay() > 31)
return false;
if (birthday.getMonth() < 1 || birthday.getMonth() > 12)
return false;
if (birthday.getYear() < 1700 || birthday.getYear() > 2100)
return false;
if (birthday.getMonth() == 2 && birthday.leapYear() && birthday.getDay() > 29)
return false;
if (!birthday.leapYear() && birthday.getMonth() == 2 && birthday.getDay() > 28 || birthday.getMonth() == 4 && birthday.getDay() > 30 || birthday.getMonth() == 6 && birthday.getDay() > 30 || birthday.getMonth() == 9 && birthday.getDay() > 30 || birthday.getMonth() == 11 && birthday.getDay() > 30)
return false;
return true;
}
关于c++使用另一个类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003758/