C++ 如何避免重新声明子方法,并且仍然为不同的子类定义不同的方法?
目前,我在Setplay.h中声明了一个父类和两个子类 在Setplay.cpp中,我定义了方法C++ 如何避免重新声明子方法,并且仍然为不同的子类定义不同的方法?,c++,inheritance,virtual,C++,Inheritance,Virtual,目前,我在Setplay.h中声明了一个父类和两个子类 在Setplay.cpp中,我定义了方法 namespace agent { int ChildSetplay1::reset(){ return 1; } int ChildSetplay2::reset(){ return 2; } } 有没有办法避免在.h中重新声明方法,并且仍然为每个子级定义唯一的方法 如果我避免在.h中重新声明方法: 然后我得到以下错误: 错误:在类“agent::ChildSetplay1
namespace agent {
int ChildSetplay1::reset(){
return 1;
}
int ChildSetplay2::reset(){
return 2;
}
}
有没有办法避免在.h中重新声明方法,并且仍然为每个子级定义唯一的方法
如果我避免在.h中重新声明方法:
然后我得到以下错误:
错误:在类“agent::ChildSetplay1”中未声明“int agent::ChildSetplay1::reset”成员函数
但是如果我将方法的签名更改为
int reset(){
return ??; // return 1? 2?
}
我不确定是否有办法做到这一点,但我的动机是:
实际的类有几个方法,并且总是重新声明一切看起来很糟糕
我仍然需要将所有内容保存在.cpp和.h中
那么,有可能吗?或者有更好的选择吗?您需要为每个子级定义函数,因此无法逃避此问题。如果您有多个函数,您可以做的是稍微转一圈,然后使用define 比如:
至少您可以保存一些东西。…需要匹配.h和.cpp,所以不需要。
namespace agent {
class Setplay {
public:
virtual int reset() {return 0;};
};
class ChildSetplay1 : public Setplay {};
class ChildSetplay2 : public Setplay {};
}
int reset(){
return ??; // return 1? 2?
}
#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
};
}