通过函数传递后,我该如何降低指针

How can I downcast a pointer after passing it through a function?

本文关键字:何降低 指针 函数      更新时间:2023-10-16

我创建了一个函数,该函数将基本指针返回到func中创建的派生对象。似乎它不起作用!好像派生数据丢失了,指针指向基本对象...

有类请求,这是基类,并且有class loginrequest-派生请求。为了检查对象的类型,我打印了对象的名称(typeId(*r(.name(((。在Func((内部,打印输出被证明为" LoginRequest",这很好,因为这是尖的对象。(查看代码(但是在返回该指针后,当我再次打印它是类型的时候,事实证明它是"请求"。你们能帮我吗?为什么返回的指针丢失了派生数据?


Request * r = new Request();
r = func(); // r is now supposed to point the LoginRequest object.
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT
//func
Request * func()
{
    Request * r;
    LoginRequest l = LoginRequest();
    r = &l;
    std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
    return r; 
}

您正在返回一个具有自动存储持续时间的对象l的指针。
删除返回的指针具有不确定的行为。

您需要使用new动态创建该对象,并删除函数外部滥用new引起的内存泄漏:

Request* func()
{
    Request* r = new LoginRequest();
    std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
    return r; 
}

// ...
Request * r = func();
std::cout << typeid(*r).name() << std::endl; //print the type of OBJECT

您正在创建本地LoginRequest对象:

LoginRequest l = LoginRequest();

接受该地址:

r = &l;

返回:

return r;

但是l在下一行上不超出范围:

}

您想在堆上创建它:

Request * func()
{
    Request * r;
    LoginRequest* l = new LoginRequest();
    r = l;
    std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
    return r; 
}

还使用智能指针而不是原始指针。