本文介绍了downcast问题在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
using std :: cout;
using std :: endl;
class Base
{
public:
void f();
void g();

int mBaseData1;

};

class Derived:public Base
{
public:


int mDerivedData1;
};

void main()
{

Base * base = new Base();
Derived * derived =(Derived *)(base); // DownCast
derived-> mDerivedData1 = 6;
cout<< derived-> mDerivedData1<< endl; // Result = 6;
}


在此代码 new base()在堆中分配内存



和 Derived * derived =(Derived *)(base)到派生



我们如何使用mDerivedData1?我不能找到我们为mDerivedData1分配内存的地方,或者当我们调用Derived的构造函数来分配mDerivedData1?

解决方案

t找到 mDerivedData1 的内存分配位置是因为没有分配内存。您已执行无效的类型投放。存储在 base 中的东西是指向 Base 实例的指针。使用类型转换告诉编译器它实际上是一个指向 Derived 实例的指针不会这样(但编译器会相信你反正因为你是一个负责)。对象仍然只是一个 Base 。如果你想要一个 Derived ,那么你需要实例化一个 Derived 。您可以使用 dynamic_cast 将 Base 指针转换为派生指针。

  Base * base = new Derived; 
Derived * derived = dynamic_cast< Derived *>(base);
derived-> mDerivedData1 = 6;


#include <iostream>
using std::cout;
using std::endl;
class Base
{
public :
    void f();
    void g();

    int mBaseData1;

};

class Derived : public Base
{
public : 


    int mDerivedData1;
};

void main()
{

    Base* base = new Base();
    Derived* derived = (Derived*)(base); // DownCast
    derived->mDerivedData1 = 6;
    cout<< derived->mDerivedData1<<endl; // Result = 6;
}

in this code new base() allocate memory in heap

and Derived* derived = (Derived*)(base) cast base to derived

how we can use mDerivedData1? i cant find where we allocate memory for mDerivedData1 or when we call constructor of Derived for allocate mDerivedData1 ?

解决方案

The reason you can't find where memory for mDerivedData1 was allocated is because no memory was allocated. You have performed an invalid type-cast. The thing stored in base is a pointer to a Base instance. Using a type-cast to tell the compiler that it's actually a pointer to a Derived instance doesn't make it so (but the compiler will believe you anyway because you're the one in charge). The object is still just a Base. If you want a Derived, then you'll need to instantiate a Derived. You can use dynamic_cast to convert the Base pointer into a Derived pointer.

Base* base = new Derived;
Derived* derived = dynamic_cast<Derived*>(base);
derived->mDerivedData1 = 6;

这篇关于downcast问题在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 18:32