【发布时间】: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