使用可选参数覆盖虚函数

sre*_*ree 3 c++ virtual inheritance optional-arguments

为什么这种印刷23作为输出; 我的期望是33.有人可以对此有所了解.

struct A {
    virtual void f() {cout << "1";}
};

/* Private inheritance */
struct B : private A {
    void f(int x = 0) {cout << "2";}
};

struct C : B {
    void f(){cout << "3";}
};

int main() {
    C obj;
    B &ref = obj;
    ref.f();
    obj.f();
}
Run Code Online (Sandbox Code Playgroud)

Aes*_*ete 5

struct中的f(int x = 0)方法B不与Anor C结构的f()方法共享签名.

  • +1.因为B :: f(int = 0)和`A :: f()`实际上是不同的,所以可以调用两种可能的候选者.因此,此调用经历**重载解析**而不是虚拟多态.选择最佳拟合候选者,在这种情况下,它是"B :: f(int = 0)".如果需要的话,我可以在标准中搜索行程(s)的确切规则,但这最终是不调用`C :: f()`的根本原因. (3认同)