为什么要从C ++接口继承

杰罗德·泰勒

我有一个要从C ++移植到Java的应用程序。我发现有一段C ++代码真的很奇怪。

typedef std::string ArgName;
typedef std::map< ArgName, AnyData > ArgumentMap;

class Arguments : public ArgumentMap
{
    public:
    // Very important note: When read finds a numeric/set argument,
    // it sets anyData.kind to Int. But STILL, it fills anyData.dString,
    // just in case. So if the ArgumentMap was built by Arguments::read,
    // the dString fields are all filled.
    bool read( int argc, char **argv );

    // remains is filled with the arguments not starting with '-'.
    bool read( int argc, char **argv, std::vector<const char*>& remains );

    // const if fails, erases arg if succeeds.
    bool getNumericParam( const ArgName& name, int& num );

    // sw is true if the switch is present. The function
    // returns false if the argument value is not empty.
    bool getSwitch( const ArgName& name, bool& sw );

    bool getSwitchConst( const ArgName& name, bool& sw ) const;

    // Returns true if the switch is present. Throws an error message if
    // if the argument value is not empty.
    bool getSwitchCompact( const ArgName& name );

    void checkEmptyArgs() const;

};

好像在原始C ++中,作者正在使其Arguments类从Map继承。这对我来说毫无意义。Map是一个接口,这意味着您不能从它继承,而只能实现它。这是在C ++中可以完成的事情,而在Java中则无法做到吗?

另外,我不明白为什么要使用typedef。我从维基百科阅读了定义

typedef是C和C ++编程语言中的关键字。typedef的目的是从更基础的机器类型[1]形成复杂的类型,并为这种组合分配更简单的名称。当标准声明繁琐,可能引起混淆或可能因一种实现而异时,通常使用它们。

但是我不明白为什么作者会在这里这样做。他们是否在说要从类AnyData继承,并且ArgumentMap应该将Map作为其字段之一?

谢尔盖·卡里尼琴科(Sergey Kalinichenko)

这对我来说毫无意义。地图是一个界面

在Java中是这样。在C ++中,它甚至不是类,而是一个类模板。C ++没有类似于Java接口的概念,尽管您可以通过虚拟继承实现类似的东西。

就集合类而言,C ++通过模板和通用编程解决了Java通过接口和继承解决的问题。

C ++映射模板的实例是功能齐全的类,其工作方式与Java的相似TreeMap您可以按照从Java类中继承的相同方式继承它们,并且由于具有多重继承,因此您不仅限于单个类。

另外,我不明白为什么要使用typedef。

typedef可以给类赋予有意义的名称。除了缩短键入内容之外,它还使程序更具可读性,并为typedef以后重新定义类提供了更大的灵活性

注意:您可以从标准容器继承的事实并不意味着您应该这样做。阅读此问题的答案以获取更多信息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章