我有这些课程:
class Field{
public:
int X;
void validate(){
validator->validate(this);
}
void setValidator(Validator* v){
validator = v;
}
private:
Validator* validator;
};
class DerivedField : public Field{
public:
int Y;
}
class Validator {
public:
virtual void validate(Field*); // do something with Field.X
};
class DerivedValidator : public Validator {
virtual void validate(Field*); //do something with DerivedField.Y
};
我想做这个:
DerivedValidator* v = new DerivedValidator();
DerivedField* f = new DerivedFiled();
f->setValidator(v);
f->validate(); // Error, Validator::validate called instead of DerivedValidator::validate
由于它不起作用,我该怎么做才能避免这种情况:
class DerivedValidator{
void validate(Field* f){
DerivedField* dv = dynamic_cast<DerivedField*>(f);
// do something with dv.Y
}
};
谢谢你。
编辑:好的,现在所有的“错误”都已修复。