我有以下两个结构,child继承自base:
struct Base{
double S1(int x){
return x*x;
}
double S2(int x){
return 2*x;
}
double S(int x){
return S1(x) + S2(x);
}
};
struct Child: Base{
double S1(int x){
return 0.0;
}
double S2(int x){
return 0.0;
}
};
S(int x)
使用 S1(int x)
和 S2(int x)
来产生结果。我想覆盖孩子的 S1
和 S2
,这似乎有效。以下输出:
Child child;
Base base;
std::cout<<child.S(2.0)<<std::endl; //<-- 8 not OK, still base S
std::cout<<child.S1(2.0)<<std::endl; //<-- 0 OK, child S1
std::cout<<base.S1(2.0)<<std::endl; //<-- 4 OK, base S1
std::cout<<base.S(2.0)<<std::endl; //<-- 8 OK, base S
8 0 4 8
这表明 S1
确实被覆盖了。然而,child.S
似乎调用了基础结构的S
,而后者又使用了基础结构的S1
和S2
函数。我怎样才能让孩子的S
(这里没有明确定义,因为它是继承的)使用覆盖的S1
和S2
?
只需将
S1
和 S2
设为虚拟
struct Base{
virtual double S1(int x){
return x*x;
}
virtual double S2(int x){
return 2*x;
}
double S(int x){
return S1(x) + S2(x);
}
};
struct Child: Base{
double S1(int x){
return 0.0;
}
double S2(int x){
return 0.0;
}
};