gpt4 book ai didi

c++ - 将向上转换指针转换为调用派生虚拟的基础对象

转载 作者:行者123 更新时间:2023-11-30 02:16:24 26 4
gpt4 key购买 nike

<分区>

我有两个类,一个派生自另一个。我想要一个返回调用派生虚函数的基类的对象(不是指针或引用)的函数。

#include <iostream>
using namespace std;

class Base
{
public:
virtual void print() { cout << "Base" << endl; }
};

class Derived : public Base
{
public:
void print() { cout << "Derived" << endl; }
};

Base go()
{
Derived *derived = new Derived();

Base *base = derived;
base->print();

// (*base).print(); // prints "Derived" !
// Base base2 = (*base);
// base2.print(); // prints "Base" !

return *base;
}

int main()
{
Base base = go();
base.print();
return 0;
}

打印出来

Derived
Base

所以在 go() 函数中,我设法转换为 Base 并且打印有效。但是当我返回对象时,打印使用的是基本函数!

我知道如果您返回一个指针或引用,这会起作用,但我确实需要返回一个对象。这可能吗?为什么我的代码不起作用?

如您所见,我在 go() 中注释掉了取消引用上行指针的代码。奇怪的是,它打印正确!如果我对一个对象进行转换,它不会!

如果能深入了解这一切发生的原因,我们将不胜感激。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com