【问题标题】:Class inheritance in C++C++中的类继承
【发布时间】:2013-02-11 09:01:39
【问题描述】:

以下代码将从 B 类调用函数 F,但有人可以向我解释为什么会这样。 B类的方法是否有可能重载V类的方法(因为B是从V继承的)?提前致谢。

#include <iostream>
using namespace std;

class V{
public: 
    void f(){ x+=2; cout << "V:"<< x;};
    int x;
};
class B: public virtual V{
public:
    void f(){ x+=3; cout << "B:"<< x;};
    int x;
};
class D: public B, virtual public V{
public:
    void g(){   x++;    f();    }
};
void main(){
    D ins;
    ins.x = 1;
    ins.g();
}

【问题讨论】:

    标签: c++ class inheritance overloading


    【解决方案1】:

    B::f() 隐藏方法V::f(),这称为函数隐藏

    好读:
    What's the meaning of, Warning: Derived::f(char) hides Base::f(double)?

    【讨论】:

      【解决方案2】:

      不,那里没有进行重载。正如上面回答的那样,B 的 f() 只是隐藏了 V 的 f(),因为 D 继承自 B 和 V,而 B 是两者中派生最多的,所以它将从 B 中获取 f()。从 V 继承 D 是不必要的,因为 V 已经包含在 B 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-09
        • 2015-12-09
        • 1970-01-01
        相关资源
        最近更新 更多