2017-03-16 23 views
-1

我想用C++中的抽象类作为接口的原因:)这样的:Javainterface作为++广义OBJECTTYPE概念用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 
    }; 

但我不能在比较方法传递基本类型,因为它是一个抽象类,我不能实例化它。 C++抱怨cannot declare parameter ‘first’ to be of abstract type ‘Base’。我怎样才能创建一个方法,它带有实现Base类的任何类的类型?

我知道这是一种类似于像thisthisthis的问题,但这些问题的答案没有帮助,因为他们不说话了如何使用接口为以任何方式推广类型。

谢谢:)

+0

不要使用Java作为编写中的C++代码的典范。任何优秀的C++书籍都会明确将'Base'参数作为引用或指针,而不是对象。 – PaulMcKenzie

+1

我不知道'first'是哪里,但是你传递的是对象而不是引用或指向对象的指针。 – jiveturkey

+0

好吧,如果我使用一个参考它的工作原理。例如,如果我想返回“较大”对象,我该如何返回?我必须使用'''模板'''那么? – KuSpa

回答

1

如何

int compare(Base const& other); 

,你会再为使用:

trueChild.compare(falseChild); 
+0

或通过参考。 – PaulMcKenzie

+0

是的,我的错误。更新了答案。 – ssell