我创建了一个函数,它返回一个指向在 func 中创建的派生对象的基指针。 好像不行啊!就好像派生数据丢失了,指针指向了一个基础对象......
有类Request,它是基类, 还有一个类loginRequest - 它派生Request。为了检查对象的类型,我打印了对象的名称(typeid(*r).name())。 在 func() 内部,打印输出结果是“loginRequest”,这很好,因为这是指向的对象。 (看代码) 但是返回这个指针后,当我再次打印它的类型时,结果是“Request”。你们能帮我吗?为什么返回的指针会丢失派生数据?
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
关于c++ - 在将指针传递给函数后,如何向下转换指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56754784/