2017-03-16 22 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