C++:访问祖父母方法

4 c++ polymorphism inheritance overloading

为什么这不起作用,什么是一个好的选择?

class Grandparent
{
    void DoSomething( int number );
};

class Parent : Grandparent
{
};

class Child : Parent
{
    void DoSomething()
    {
        Grandparent::DoSomething( 10 ); // Does not work.
        Parent::DoSomething( 10 ); // Does not work.
    }
};
Run Code Online (Sandbox Code Playgroud)

Jos*_*erg 12

class Grandparent
{
protected:
    void DoSomething( int number );
};

class Parent : protected Grandparent
{
};

class Child : Parent
{
    void DoSomething()
    {
        Grandparent::DoSomething( 10 ); //Now it works
        Parent::DoSomething( 10 ); // Now it works.
    }
};
Run Code Online (Sandbox Code Playgroud)

至少它需要看起来像这样.在使用类时,默认情况下是私有的,这包括子类.

http://codepad.org/xRhc5ig4

有一个完整的例子可以编译和运行.

  • 请注意,`struct`的成员默认是公共的.事实上,`class`和`struct`之间的唯一区别是`class`成员默认是私有的,`struct`成员默认是public. (4认同)
  • 对于记录,面向对象的继承的一般概念通常在C++中实现为_public_继承.我建议初学者总是使用`class Subclass:public Superclass`. (2认同)