c++ - 递归虚拟调用不能正常工作?

标签 c++ recursion

我有这个代码:

#include <iostream>
#include <string>
using namespace std;

struct Flower
{
    virtual string str() = 0;
};

struct Rose : Flower
{
    string str() override { return "A rose"; }
};

struct RedFlower : Flower
{
    Flower& flower;
    RedFlower(Flower& flower) : flower{ flower } {}
    string str() override { return flower.str() + " that is red"; }
};

int main()
{
    Rose rose;
    RedFlower red_rose{ rose };
    RedFlower red_red_rose{ red_rose };
    RedFlower red_red_red_rose{ red_red_rose };
    cout << rose.str() << endl;
    cout << red_rose.str() << endl;
    cout << red_red_rose.str() << endl;
    cout << red_red_red_rose.str() << endl;
}
它打印出来
A rose
A rose that is red
A rose that is red
A rose that is red
不应该打印出来吗
A rose
A rose that is red
A rose that is red that is red
A rose that is red that is red that is red
???为什么不打印它应该打印的内容?编译器是否优化了调用,或者类层次结构是否随之丢失?我似乎没有指出我错过的究竟是什么。我知道我的代码一定有问题。我相信动态多态性在调用堆栈中的某处丢失了......?

最佳答案

这里的问题是,编译器会自动生成一个具有以下签名的复制构造函数:

RedFlower(RedFlower const &)
正在调用该构造函数而不是您的自定义构造函数。一种解决方案是向 Flower & 添加显式强制转换:
Rose rose;
RedFlower red_rose{ rose };
RedFlower red_red_rose{ static_cast<Flower &>(red_rose) };
RedFlower red_red_red_rose{ static_cast<Flower&>(red_red_rose) };

关于c++ - 递归虚拟调用不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64503937/

相关文章:

c++ - 通过用户输入在 C++ 中查找最大值和最小值

c++ - 奇怪的 GetTickCount 问题

c# - 为什么在这个例子中使用 float 比使用 double 慢 2 倍?

c++ - 如何动态链接grpc库c++?

c++ - 防止 gcc 将我的 AVX2 内在函数拷贝损坏到 REP MOVS 中

javascript - 如何使用递归计算数组中数字的实例?

java - 为什么时间复杂度是n*n*n!对于以下算法打印字符串的所有排列?

php - 使用 PHP 将大型递归函数保持在最低限度

C++11 constexpr 函数编译器错误与三元条件运算符 (? :)

c - C中的递归strstr函数