如何避免 re-declaring child 方法并仍然为不同的 child 类 定义不同的方法?

How to avoid re-declaring child methods and still define different methods for different child classes?

目前,我在 Setplay.h 中声明了一个 parent class 和 2 个 child class,因此

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;
}

}

有没有办法避免 re-declaring .h 中的方法,并且仍然为每个 child 定义唯一的方法?

如果我避免 re-declaring .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’

但是如果我将方法的签名更改为

之类的东西,我就无法为每个 child 定义不同的方法
int reset(){
    return ??; // return 1? 2?
}

我不确定是否有办法做到这一点,但我的动机是:

所以,可能吗?或者有更好的选择吗?

你需要为每个child定义函数,所以你无法逃避这个。你可以做的是,如果你有多个功能,可以稍微绕一下并使用 #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
};

}

至少能省点事.....