为什么我可以用孙子 object 调用祖父母方法?我读到这是不可能的

why am I able to call grandparent method with grandchild object? I read that it was not possible

这是我从网上得到的代码... 以及 virtual 关键字是如何工作的? 我认为此虚拟关键字与此行为有关,但我不明白它是什么。

class A {
    int x;

public:
    A(int i) { x = i; }
    void print() { cout << x; }
};

class B : virtual public A {
public:
    B()
        : A(10)
    {
    }
};

class C : virtual public A {
public:
    C()
        : A(10)
    {
    }
};

class D : public B, public C {
};

int main()
{
    D d;
    d.print();
    return 0;
}

why am I able to call grandparent method with grandchild object?

因为这就是继承的工作原理。该成员函数被 child class 和宏大的 child.

继承

I read that it was not possible

要么你读错了,要么你误解了。

how virtual keyword is working?

当一个虚拟基地在层次结构中多次出现时,这些出现将合并为一个基地子 object。

在 D 的情况下,B 的基数 A 和 C 的基数 A 是相同的基数,如果继承不是虚拟的,情况就不会如此。

您的假设可能是正确的,但这并不容易。

print 声明为 public 成员函数。由于您使用 public 派生每个 class,您仍然可以从 D class 对象调用 print

如果您想要描述的行为,一种方法是,您必须重写 class

class A {
    int x;

public:
    A(int i) { x = i; }

private:
    void print() { cout << x; }
};

你应该研究 'inheritance' 的话题。您可以从 ARTICLE.

开始

一般来说,菱形 class 结构表示软件设计不佳。是的,创建这样的东西可能有一些充分的理由。但是判断问题的类型,你真的应该忘记它并避免它。除非你真的确定你在做什么。

您找到的结构描述为 here