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

Sai*_*000 5 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;
}
Run Code Online (Sandbox Code Playgroud)

它打印出来

A rose
A rose that is red
A rose that is red
A rose that is red
Run Code Online (Sandbox Code Playgroud)

不应该打印出来吗

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
Run Code Online (Sandbox Code Playgroud)

???为什么不打印它应该打印的内容?编译器是否优化了调用,或者类层次结构是否随之丢失?我似乎没有指出我错过的究竟是什么。我知道我的代码一定有问题。我相信动态多态性在调用堆栈中的某处丢失了......?

chu*_*ill 3

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

RedFlower(RedFlower const &)
Run Code Online (Sandbox Code Playgroud)

正在调用该构造函数而不是您的自定义构造函数。一种解决方案是添加显式强制转换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) };
Run Code Online (Sandbox Code Playgroud)