`dynamic_cast`从Base到Derived [英] `dynamic_cast` from Base to Derived
问题描述
是的,我知道,如果 Base
不是多态,但是使用 dynamic_cast
问题不在这。
Yes, I know that downcast using dynamic_cast
can't compile if the Base
is not polymorphic, but my problem is not about this.
class Base {
public:
virtual void bar()
{
cout << "bar\n";
}
};
class Derived: public Base {
public:
void foo()
{
cout << "foo\n";
}
};
int main()
{
Base *pb;
Derived *pd;
pb = new Derived; //Base* points to a Derived object
pd = dynamic_cast<Derived*>(pb);
pd->foo(); //outputs foo
pb = new Base; //Base* points to a Base object
pd = dynamic_cast<Derived*>(pb);
pd->foo(); //outputs foo, too. Why?
}
我想当 pb = new Derived; code>,
pb
实际上指向一个 Derived
对象位于堆中。 pd = dynamic_cast< Derived *>(pb);
, pd
之后还指向 Derived
对象,因此 pd-> foo()
应该可以。
I thought when pb = new Derived;
, pb
actually points to a Derived
object lies in heap. After pd = dynamic_cast<Derived*>(pb);
, pd
also points to that Derived
object, so pd->foo()
should be OK.
但是当 pb = new Base;
时, pb
指向是 Base
对象在堆中,然后在
pd = dynamic_cast< Derived *>(pb);
,如何 pd-> foo ()
工程? dynamic_cast
将堆中的 Base
对象变成 Derived
对象?
But when pb = new Base;
, what pb
points to is a Base
object in heap, then after pd = dynamic_cast<Derived*>(pb);
, how could pd->foo()
works? Did dynamic_cast
turn the Base
object in heap into a Derived
object?
推荐答案
在C ++中,类的每个实例都有自己的数据类型版本,存储器(内联函数除外)。在你的情况下,当你说如下:
In C++, each instance of a class has its own version of datatypes, but all classes share the same function in memory (other than for inline functions). In your case, when you say something like:
pd->foo();
你实际上是调用 Derived :: foo
,这是内存中的函数,编译器知道它在哪里。事情是,它不依赖于 pd
。但是,如果你有这样的:
You are essentially calling Derived::foo
, which is a function in memory and the compiler knows where it is. The thing is, it is not dependent on pd
at all. However, if you had something like this:
class Derived : public Base {
private:
int a;
public:
Derived() { a = 100; }
void foo() {
std::cout<<a<<std::endl;
}
};
然后, pd-> foo()
将导致分段故障。这里,您的动态转换失败,当调用 Derived :: foo
时,它会通过 0
c $ c> this 对象。在以前的情况下,因为这个
对象从来没有使用是很好。然而,在第二种情况下,它被使用,因此导致分段错误。
Then, pd->foo()
will cause a Segmentation fault. Here, your dynamic cast has failed and when Derived::foo
is called, it is passed 0
as the this
object. It was fine in the previous case, as the this
object was never used. However, in the second case, it is used and hence, causes a Segmentation fault.
这篇关于`dynamic_cast`从Base到Derived的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!