如何在C ++中实现接口 [英] How to implement an interface in C++

查看:267
本文介绍了如何在C ++中实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个作业,试图理解一些东西.我有一条指令来创建两个接口:IComparableIPrintable.另外,我需要创建一个名为Interval的模板.

I have an assignment and trying to understand something. I have an instruction to create two interfaces: IComparable and IPrintable. Also, I need to create a template called Interval.

我得到了main函数,我需要相应地实现这些类,这样它才能按预期工作.

I am given the main function and I need to implement these classes accordingly so it will work as intended.

这是我当前正在实现的功能(注释显示输入的外观):

This is the function I am currently implementing (the comments displays what the input should look like):

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被认为是接口而不是模板.

If you will look at code, you can see where I am stuck and that's my problem: As far as I know, this type of writing is using templates. But in the instructions, IComparable is said to be an interface and not a template.

如何使用接口实现此目的?我可以使用接口来实现它吗?

How can I implement this using an interface? Can I implement it using an interface?

这是我的Date.cpp:

This is my 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;
}

推荐答案

什么不起作用?

让我们撤离您的线路问题:您不需要 dynamic_cast 实现多态. dynamic_cast仅应在非常特殊的情况下使用.为了使转换成功,它需要源类型和目标类型(此处为DateIComparable<Date>)之间的某种继承关系.不幸的是,如果没有类定义和错误消息,就无法提供进一步的建议.

What doesn't work ?

Let's evacuate your line issue: You do not need dynamic_cast to implement polymorphism. dynamic_cast should only be used in very specific cases. And the cast to succeed, it requires some inheritance relations between the source and target types (here Date and IComparable<Date>). Unfortunately, without the class definitions and the error message, it's not possible to advise further.

您是对的:IComparable<Date>是模板,而不是接口.

You are right: IComparable<Date> is a template, and not an interface.

接口不是C ++语言功能.但是关于它是什么有一个共同的理解:这是一个没有功能的类,旨在保证将由其他类实现的行为. C ++标准以这种方式描述了这一点(在脚注中,仅是指示性的):

Interfaces are not a C++ language feature. But there is a common understanding about what it is: it's a class with no functionality that is meant to promise a bahavior that will be implemented by other classes. The C++ standard describes it this way (in a foot note, so it's indicative only):

抽象类也可以用于定义一个接口,派生类可为其提供各种实现

An abstract class can also be used to define an interface for which derived classes provide a variety of implementations

这些函数必须是虚拟的才能获得多态行为.此外,抽象类是具有纯虚函数(即未定义的函数)的类,因此永远不能直接实现.

The functions have to be virtual to get the polymorphic behavior. Abstract classes are furthermore classes that have pure virtual functions (i.e. functions that are not defined) and that can therefore never be implemented directly.

一般想法是:

 class IComparable {
 public:  
    virtual bool is_equal(const IComparable &a, const IComparable &b) = 0;  
    virtual bool is_lesser(const IComparable &a, const IComparable &b) = 0;  
    ... // whetever else you want
    virtual ~IComparable(){};    // good practice: one virtual function -> virtual destructor
 };  

然后您可以让Date实现它:

class Date : public IComparable {
public:
    bool is_equal(const IComparable &a, const IComparable &b) override; 
    ... // you SHOULD override all the pure virtual of the interface
}; 

这篇关于如何在C ++中实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆