gpt4 book ai didi

c++ - 试图用多态来沮丧,出了什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:49 24 4
gpt4 key购买 nike

我有两个指向基类的指针,一个指向实际的基对象,另一个指向派生对象。我还有一个为基类和派生类重载的非成员函数。我想使用多态性来向下转换指针,以便调用正确的重载。

代码的输出是

base downcast called
base
derived downcast called
base

然而期望的输出是

base
derived

谁能解释输出结果,以及必须做什么才能获得所需的行为?

#include <iostream>
using namespace std;

class base
{
public:
virtual base& downcast()
{
cout << "base downcast called" << endl;
return *this;
}
};

class derived: public base
{
public:
virtual derived& downcast()
{
cout << "derived downcast called" << endl;
return *this;
}
};

void foo(const base& a)
{
cout << "base" << endl;
}

void foo(const derived& a)
{
cout << "derived" << endl;
}


int main()
{
base* ptr1 = new(base);
base* ptr2 = new(derived);

foo(ptr1->downcast());
foo(ptr2->downcast());

return 0;
}

编辑:向向下转换函数添加 cout 以说明函数覆盖/多态性。

最佳答案

您基本上是在尝试使运行时多态性影响编译时重载解析。由于显而易见的原因,这是不可能的。函数重载是一种编译时特性,这意味着重载解析是在编译时根据函数参数的静态类型执行的。

在您的情况下,选择调用哪个 foo 是基于 static 类型化:static 类型的 ptr1ptr2 以及 static 类型的 ptr1->downcast()ptr2->downcast()返回值。在这两种情况下,后者都是 base 类型的左值(引用)。选择 foo 不涉及多态性。编译器不知道(也不关心)在运行时这些 base & 引用之一实际上会引用 derived 对象。

但是,如果您可以从 foo 调用 a.downcast(),您会发现朗姆酒时间多态性在 foo 中仍然有效>。 (此时由于 downcast() 是非常量,这样的调用是不可能的)

关于c++ - 试图用多态来沮丧,出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40511868/

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