2017-07-17 11 views
0

目前,我在Setplay.h聲明父類和2個類,因爲這樣的如何避免再次宣佈孩子的方法和仍然定義不同子類中不同的方法?

namespace agent { 

class Setplay { 
public: 
    virtual int reset() {return 0;}; 
}; 

class ChildSetplay1 : public Setplay { 
public: 
    virtual int reset(); 
}; 

class ChildSetplay2 : public Setplay { 
public: 
    virtual int reset(); 
}; 

} 

而且在Setplay.cpp,我定義的方法

namespace agent { 

int ChildSetplay1::reset(){ 
    return 1; 
} 

int ChildSetplay2::reset(){ 
    return 2; 
} 

} 

有沒有一種辦法避免再次宣佈在.h方法,仍然定義爲每個孩子獨特的方法?

如果我避免重複申報方法在.h

namespace agent { 

class Setplay { 
public: 
    virtual int reset() {return 0;}; 
}; 

class ChildSetplay1 : public Setplay {}; 
class ChildSetplay2 : public Setplay {}; 

} 

然後我得到以下錯誤:

error: no ‘int agent::ChildSetplay1::reset()’ member function declared in class ‘agent::ChildSetplay1’

但我不能定義不同的爲每一個孩子,如果方法我將方法的簽名更改爲類似

int reset(){ 
    return ??; // return 1? 2? 
} 

我不知道是有辦法做到這一點,但我的動機是:

  • 實際類有幾種方法,並重新申報所有一切的時間長得難看

  • 我還需要保持.cpp.h

所以裏面的一切,是有可能?或者有沒有更好的方法?

+0

h和。 CPP需要匹配所以沒有。 –

回答

1

您需要定義函數每一個孩子,讓你無法逃避這一點。你可以做什麼,都是圍繞走一點點,使用#define如果您有多個功能 像:

#define SET_PLAY_FUNCTIONS public:\ 
          virtual int reset();\ 
          virtual int go(); 
namespace agent { 

class Setplay { 
public: 
    virtual int reset() {return 0;}; 
    virtual int go(); 
}; 

class ChildSetplay1 : public Setplay { 
    SET_PLAY_FUNCTIONS 
}; 

class ChildSetplay2 : public Setplay { 
    SET_PLAY_FUNCTIONS 
}; 

} 

至少可以節省一些.....

相關問題