我有这个简单的代码:
#include <iostream>
using namespace std;
class GenericMove {};
class SwapMove: public GenericMove {};
class SoftConstraint {
public:
virtual int evaluate(GenericMove& gm) = 0;
};
class M1: public SoftConstraint {
public:
int evaluate(GenericMove& gm){ return 1; }
int evaluate(SwapMove& gm){ return 2; }
};
int main () {
M1 m1;
GenericMove* swapmove = new SwapMove();
cout << "Hello " << m1.evaluate(*swapmove) << endl;
return 0;
}
我想在 M1 的 evaluate
函数中区分 GenericMove 和 SwapMove,所以我希望主要打印“Hello 2”。
有没有办法区分swapmove
不仅是简单的GenericMove,还是M1内部的SwapMove?
这在 C++ 中可能吗? 提前致谢!
最佳答案
不,这在 C++ AFAIK 中不是直接可行的,但您可以使用 double dispatch以达到您想要的结果。
class GenericMove;
class SwapMove;
class SoftConstraint {
public:
virtual int evaluate(GenericMove& move) = 0;
virtual int evaluate(SwapMove& move) = 0;
};
class M1 : public SoftConstraint {
public:
int evaluate(GenericMove& move) { return 1; }
int evaluate(SwapMove& move) { return 2; }
};
class GenericMove {
public:
virtual int evaluate(SoftConstraint& constraint) {
return constraint.evaluate(*this);
}
};
class SwapMove : public GenericMove {
public:
int evaluate(SoftConstraint& constraint) {
return constraint.evaluate(*this);
}
};
int main () {
M1 m1;
GenericMove* swapmove = new SwapMove();
std::cout << "Hello " << swapmove->evaluate(m1) << std::endl;
return 0;
}
请注意,在我的提议中,您必须调用移动实例的 evaluate
方法,而不是调用约束的 evaluate
方法。但这很容易改变。
双重分派(dispatch)利用了这样一个事实,即 this
指针的静态类型始终是使用 this
指针的函数所属的类型。在我们的示例中,GenericMove::evaluate
中 this
的静态类型是 GenericMove*
,因此对 SoftConstraint::evaluate
的调用选择了将对 GenericMove
实例的引用作为其参数的函数。另一方面,SwapMove::evaluate
中 this
的静态类型是 SwapMove*
,因此对 SoftConstraint::evaluate
的调用选择了将对 SwapMove
实例的引用作为其参数的函数。
双重分派(dispatch)允许您使用调用接收者的类型和一个参数的类型来选择一个方法。
关于c++ - 用继承的类覆盖相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626389/