【问题标题】:How to avoid re-declaring child methods and still define different methods for different child classes?如何避免重新声明子方法,仍然为不同的子类定义不同的方法?
【发布时间】:2017-07-17 13:23:00
【问题描述】:

目前,我在Setplay.h 中声明了一个父类和两个子类,因此

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

}

然后我得到以下错误:

错误:在类“agent::ChildSetplay1”中没有声明“int agent::ChildSetplay1::reset()”成员函数

但是如果我将方法的签名更改为类似的东西,我无法为每个孩子定义不同的方法

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

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

  • 实际的类有几个方法,而且总是重新声明一切看起来很难看

  • 我仍然需要将所有内容保存在 .cpp.h

那么,有可能吗?还是有更好的选择?

【问题讨论】:

  • .h 和 .cpp 需要匹配所以不行。

标签: c++ inheritance virtual


【解决方案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
};

}

至少你可以保存一些东西.....

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2015-12-18
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多