为什么可以继承C++中的接口

j.j*_*lor 1 c++ inheritance c++11

我有一个应用程序,我正在从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;

};
Run Code Online (Sandbox Code Playgroud)

看起来在原始C++中,作者正在使他们的Arguments类继承自Map.这对我来说毫无意义.Map是一个接口,意味着你不能从它继承,你只能实现它.这是可以用C++完成的,你不能用Java做的吗?

另外,我不明白你为什么要使用typedef.我从维基百科中读到了这个定义

typedef是C和C++编程语言中的关键字.typedef的目的是从更基本的机器类型[1]形成复杂类型,并为这种组合分配更简单的名称.它们最常用于标准声明繁琐,可能令人困惑,或者可能因实现而异

但我不明白为什么作者会这样做.他们是否试图说他们想继承AnyData类并且ArgumentMap应该将Map作为其中一个字段?

das*_*ght 6

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

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

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

C++映射模板的实例是完全正常运行的类,其工作方式与Java类似TreeMap.您可以使用与从Java继承的相同方式继承它们,并且由于多重继承,您不仅限于单个类.

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

typedef用来为类提供有意义的名称.除了缩短您的输入外,它还使您的程序更具可读性,并为您重新定义后面的类提供了额外的灵活性typedef.

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