【发布时间】:2020-04-30 04:54:45
【问题描述】:
我有一个任务并试图理解一些东西。我有一个创建两个接口的指令:IComparable 和IPrintable。另外,我需要创建一个名为Interval 的模板。
我得到了main 函数,我需要相应地实现这些类,这样它才能按预期工作。
这是我目前正在实现的功能(cmets 显示输入应该是什么样子):
void testDate() {
Date independence(14, 5, 1948);
cout << independence << endl;
Date otherDate = independence;
cout << "Independence:" << independence << ", Other: " << otherDate << endl; // Independence:14/05/1948, Other: 14/05/1948
otherDate.setMonth(2);
cout << "Other date: " << otherDate << endl; // Other date: 14/02/1948
otherDate.setDay(29);
cout << "Other date: " << otherDate << endl; // Other date: 29/02/1948
otherDate.setYear(1947);
cout << "Other date: " << otherDate << endl; // Other date: Not a leap year
otherDate = Date(24, 1, 1959);
cout << "Other date: " << otherDate << endl; // Other date: 24/01/1959
cout << "Comparing using polymorphism" << endl; // Comparing using polymorphism
IComparable<Date> *indP = dynamic_cast <IComparable<Date> *> (&independence);
/* --------------------------- ^^^ Stuck in the line above ^^^ --------------------------- */
cout << "Is independence <= otherDate ? " << (*indP <= otherDate) << endl; // Is independence <= otherDate ? true
IComparable<Date> *otherP = dynamic_cast <IComparable<Date> *> (&otherDate);
cout << "Is other date <= independence ? " << (*otherP <= independence) << endl; // Is other date <= independence ? false
}
如果您查看代码,您可以看到我卡在哪里,这就是我的问题:
据我所知,这种写作是使用模板。但在说明中,IComparable 被说成是一个接口而不是一个模板。
如何使用接口实现这一点?我可以使用接口来实现它吗?
这是我的 Date.cpp:
#include <iostream>
#include "Date.h"
#include "IComparable.h"
using namespace std;
void Date::setDay(int d) { day = d; }
int Date::getDay() const { return day; }
void Date::setMonth(int m) { month = m; }
int Date::getMonth() const { return month; }
void Date::setYear(int y) { year = y; }
int Date::getYear() const { return year; }
Date::Date(int d, int m, int y) {
setDay(d);
setMonth(m);
setYear(y);
}
void Date::operator= (const Date& other) {
day = other.getDay();
month = other.getMonth();
year = other.getYear();
}
void Date::toOs(ostream& output) const {
// TODO : Check if leap year!
output << getDay() << "/" << getMonth() << "/" << getYear();
}
bool Date::isLeapYear(int yearToCheck) const {
if (yearToCheck % 4 == 0)
{
if (yearToCheck % 100 == 0)
{
if (yearToCheck % 400 == 0)
return true;
else
return false;
}
else
return false;
}
else
return false;
return false;
}
【问题讨论】:
-
一个接口定义了你的类需要实现的一个或多个纯虚方法。一个界面可能使用也可能不使用模板(可能更频繁。他们不使用)。因此,您需要定义类
IComparable和IPrintable,然后从这些类派生并在您的具体类中实现这些功能。阅读“C++ 接口”和“虚拟基类”。 -
一个minimal reproducible example 会很有帮助,因为代码的重要部分没有包括在内,并且提供了很多不相关的代码。
-
我想不出那些
dynamic_casts 有任何意义的情况。该代码仅在Date派生自IComparable<Date>时才有效,在这种情况下,任何强制转换都是不必要的。 -
A
dynamic_cast通常对指向堆栈值的指针毫无意义。即使出于极少数原因,您希望有一个指向基类型的值,您也可以使用static_cast。 -
代码的哪一部分给了你,你写了哪一部分?
标签: c++ oop inheritance interface implementation