[英]Implementation of a pure virtual function in C++
Given the following scenario, I have a base class MyBaseClass
with a pure virtual function void foo() = 0;
给定以下情况,我有一个带有纯虚函数
void foo() = 0;
的基类MyBaseClass
void foo() = 0;
. 。 Two classes
MyClassA
and MyClassB
are derived from that class MyBaseClass
. 从该类
MyBaseClass
派生两个类MyClassA
和MyClassB
。 Both implement the function foo()
. 两者都实现功能
foo()
。 Now in a project I work on, I came across an object created from class MyBaseClass
on which the function foo()
is called. 现在在我从事的项目中,我遇到了一个从类
MyBaseClass
创建的对象,在该对象上调用了foo()
函数。 Interestingly, it's the implementation from MyClassB
that is used. 有趣的是,使用的是
MyClassB
的实现。 Where is defined that it's this implementation and not the one from MyClassA
在哪里定义的是此实现而不是
MyClassA
The object was of type MyClassB
not MyBaseClass
. 该对象的类型为
MyClassB
而不是MyBaseClass
。 MyBaseClass
is abstract and cannot be instantiated. MyBaseClass
是抽象的,无法实例化。 However you probably had a pointer MyBaseClass*
which was pointing to an instance of MyClassB
. 但是,您可能有一个指向
MyClassB
实例的指针MyBaseClass*
。
You should probably read up on inheritance and polymorphism in C++ if you need some more information. 如果需要更多信息,您可能应该阅读C ++中的继承和多态性。
MyBaseClass base; // Compiler error, cannot instantiate abstract class
MyClassA a;
MyClassB b;
MyBaseClass* pA = &a;
MyBaseClass* pB = &b;
pA->foo(); // Uses implementation of foo in MyClassA
pB->foo(); // Uses implementation of foo in MyClassB
I came across an object created from class MyBaseClass
我遇到了一个从类MyBaseClass创建的对象
No, you did not. 不,你没有。 Objects of type
MyBaseClass
can't exist. MyBaseClass
类型的对象不存在。 The class is abstract and cannot be instantiated. 该类是抽象的,无法实例化。
You likely came about a pointer to a MyBaseClass
, which can point to any objects of classes that inherit the base class. 您可能
MyBaseClass
了指向 MyBaseClass
的指针 ,该指针可以指向继承基类的类的任何对象。
Is there a way of calling the implementation of MyClassA although pA is pointing to an object of class MyClassB?
尽管pA指向MyClassB类的对象,有没有一种方法可以调用MyClassA的实现? Maybe with a cast?
也许有演员表?
You can call 你可以打电话
pA->MyBaseClass::foo();
but this will only work if the function is implemented. 但这仅在实现该功能的情况下有效。 (yes, you can provide an implementation for pure method)
(是的,您可以提供纯方法的实现)
It is important to notice the difference between these snippets: 重要的是要注意这些片段之间的区别:
struct X
{
virtual void foo() = 0;
};
X x; // not valid! X has purely virtual methods
and 和
struct X; // as above
struct Y : X
{
void foo() {}
void bar() {}
};
X * x = new Y; // valid!
The second case is most likely what you have seen. 第二种情况很可能是您所看到的。 In this pattern you can call
x->foo();
在这种模式下,您可以调用
x->foo();
and it will call Y::foo()
. 它将调用
Y::foo()
。 Note that you cannot, however, call x->bar()
because X::bar()
does not exist. 请注意,但是您不能调用
x->bar()
因为X::bar()
不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.