[英]Public virtual method overridden as protected in inherited class
I have a protected abstract virtual method myMethod()
defined in class C. Class D inherits from C and defines myMethod()
. 我有一个受保护的抽象虚方法
myMethod()
在类C中定义。类D继承自C并定义myMethod()
。 Now class E also inherits from C and also defines myMethod()
. 现在,E类也继承自C,并且还定义了
myMethod()
。 So I have something like this: 所以我有这样的事情:
This looks like this 这看起来像这样
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*/};
}
Now if in D::anotherMethod()
I have a pointer to an object of class E then I cannot call E::myMethod()
. 现在如果在
D::anotherMethod()
我有一个指向E类对象的指针,那么我就不能调用E::myMethod()
。 Nothing wrong here: D and E have different hierarchies hence I cannot call E::myMethod()
from D. ie the below code does not compile which is expected: 这里没有错:D和E有不同的层次结构因此我不能从D调用
E::myMethod()
,即下面的代码不能编译预期的:
void D::anotherMethod()
{
E* myE = new E();
myE->myMethod();
}
Now if I change the declaration of C and make E::myMethod()
public (while keeping the overridden method in D and E protected
), such as in the code below, it compiles: 现在,如果我更改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*/};
}
I only changed public
to protected
inside C, not in the inherited classes D and E. 我只将
public
更改为protected
内部C,而不是继承的类D和E.
Does anyone know why it compiles and what is the logic behind it? 有谁知道为什么编译它背后的逻辑是什么?
Thanks! 谢谢!
Antoine. 安托万。
We can use C
interface as it is public: E
interface is protected and D
can't access from E
but can from base class C
我们可以使用
C
接口,因为它是公共的: E
接口受保护, D
不能从E
访问,但可以从基类C
As follow: 如下:
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();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.