如何正确重写C++中的基类函数?

问题描述 投票:0回答:1

我有以下两个结构,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

c++ c++11 overriding
1个回答
0
投票

只需将

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;
    }
};

© www.soinside.com 2019 - 2024. All rights reserved.