我有这个代码:
#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/