c++ - 公共(public)虚方法在继承类中被重写为 protected

标签 c++ inheritance polymorphism

我在 C 类中定义了一个 protected 抽象虚方法 myMethod()。D 类继承自 C 并定义了 myMethod()。现在类E也继承自C,也定义了myMethod()。所以我有这样的东西:

看起来像这样

class C
{
protected:
    virtual void myMethod() = 0;
}

class D : public class C
{
protected:
    void myMethod() {/*Do something*/};

    void anotherMethod();
}

class E : public class C
{
protected:
    void myMethod() {/*Do something else*/};
}

现在如果在 D::anotherMethod() 中我有一个指向类 E 的对象的指针,那么我不能调用 E::myMethod()。这里没有错:D 和 E 有不同的层次结构,因此我不能从 D 调用 E::myMethod()。即下面的代码无法编译,这是预期的:

void D::anotherMethod()
{
    E* myE = new E();

    myE->myMethod();
}

现在,如果我更改 C 的声明并使 E::myMethod() 公开(同时保持 D 和 E 中的重写方法 protected),例如下面的代码,它编译:

class C
{
public:
    virtual void myMethod() = 0;
}

class D : public class C
{
protected:
    void myMethod() {/*Do something*/};

    void anotherMethod();
}

class E : public class C
{
protected:
    void myMethod() {/*Do something else*/};
}

我只在 C 中将 public 更改为 protected,而在继承类 D 和 E 中没有更改。

有谁知道为什么会编译,背后的逻辑是什么?

谢谢!

安托万。

最佳答案

我们可以使用 C 接口(interface),因为它是公共(public)的: E 接口(interface)受到保护,D 无法从 E 访问,但可以从基类 C

访问

如下:

class C
{
public:
    virtual void myMethod() = 0;
};

class E : public C
{
protected:
    void myMethod() {/*Do something else*/};
};


class D : public C
{
protected:
    void myMethod() {/*Do something*/};

    void anotherMethod(){
        //C* myE = new E(); // does compile
        E* myE = new E(); // doesn't compile

        myE->myMethod();
    }
};

关于c++ - 公共(public)虚方法在继承类中被重写为 protected ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20995384/

相关文章:

c++ - 使用 memcpy 时出现内存错误?

c++ - 单例继承,派生类无法在父类中实例化?

scala - Scala 中具有抽象类型的 F 界多态性

objective-c - 继承的工厂方法应该做什么?

java - 阐述 : Method overloading is a static/compile-time binding but not polymorphism. 将静态绑定(bind)与多态性相关联是否正确?

html - 将 C++ 字符串放入 HTML 代码中以在网络服务器上显示值

c++ - 登录 HTTP 服务器 c++

c++ - 删除不需要的字符

java - 将具体类对象持久化到数据库时,将抽象类中的字段设置为强制字段

c++ - 关于c++继承的困惑