【问题标题】:Javainterface as generalized objecttype Concept in C++Java 接口作为 C++ 中的广义对象类型概念
【发布时间】:2017-03-16 21:56:36
【问题描述】:

我想在 C++ 中使用抽象类作为接口,原因如下:

    class Base{
    public:
        virtual bool foo() = 0;
        int getValue() {return this->value;};

        int compare(Base other) {
            //calculate fancy stuff using Base::foo() and other given stuff through inheritance
            return result;
        }

    protected:
        int value;
    };

    class TrueChild: public Base{
    public:
        TrueChild(int value): Base() { this->value = value;}
        bool foo() {return 1;}
        //do stuff with value
    };

    class FalseChild: public Base{
    public:
        FalseChild(int value): Base() { this->value = value;}    
        bool foo() {return false;}
        //do other stuff with value
    };

但是我不能在 compare 方法中将 Base 作为类型传递,因为它是一个抽象类,我不能实例化它。 C++ 抱怨 cannot declare parameter ‘first’ to be of abstract type ‘Base’ 。如何创建一个方法,该方法采用任何类的类型的参数,实现基类?

我知道这有点类似于thisthisthis 之类的问题,但这些答案没有帮助,因为它们没有以任何方式谈论如何将接口用作通用类型.

谢谢你:)

【问题讨论】:

  • 在编写 C++ 代码时不要使用 Java 作为模型。任何好的 C++ 书籍都会明确地将 Base 参数作为引用或指针,而不是对象。
  • 我不知道first 在哪里,但您传递的是对象而不是对象的引用或指针。
  • 好的,如果我使用参考它可以工作。例如,如果我想返回“更大”的对象,我应该返回什么?那么我必须使用template <typename T> 吗?
  • 首先了解C++,存在Java中不存在的东西——对象切片。您不能返回或传递基类,并且在调用者中,可以使用完整的对象。原因是该对象的派生部分已被“切掉”——你试图将 10 磅土豆塞进一个 5 磅的袋子里。你返回一个 Base 对象,你会得到一个Base 对象 -- 你传递了一个 Base,对象你传递了一个 Base 对象。您不能像在 Java 中那样从 Base 对象强制转换为派生对象。
  • 有什么解决办法吗?

标签: c++ interface


【解决方案1】:

怎么样

int compare(Base const& other);

然后您将用作:

trueChild.compare(falseChild);

【讨论】:

  • 或者通过引用传递。
  • 是的,我的错。更新了答案。
猜你喜欢
  • 2016-08-30
  • 2016-02-15
  • 2013-03-30
  • 2011-10-20
  • 2021-09-29
  • 2019-05-17
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多