我正在尝试一个无效的代码。发生的情况是,在写入输出时,即使初始化了颜色字符串,它也会变空。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct Shape {
virtual string str() const = 0;
};
struct Circle : Shape {
Circle() = default;
string str() const override {
ostringstream oss;
oss << "Circle";
return oss.str();
}
};
struct ColoredShape : Shape {
Shape& shape;
string color;
ColoredShape(Shape& shape, /*const string&*/string color) : shape(shape), color(color) {}
string str() const override {
ostringstream oss;
oss << shape.str() << " has the color " << color << endl;
return oss.str();
}
};
int main()
{
Circle circle;
ColoredShape v1{ circle, "v1" };
ColoredShape v2{ v1, "v2" };
ColoredShape v3{ v2, "v3" };
cout << v3.str() << endl;
/* Output is
Circle has the color v1
has the color v2
has the color v3
*/
ColoredShape n3{ ColoredShape{ ColoredShape{ circle, "v1" }, "v2" }, "v3" };
cout << n3.str() << endl;
/* Output is (no colors)
Circle has the color
has the color
has the color v3
*/
return 0;
}
我不知道为什么会这样。在上面的代码中,初始化完全相同,除了第二个初始化是在另一个结构中初始化的。你能帮忙吗?
谢谢
答案 0 :(得分:1)
ColoredShape{ ColoredShape{ circle, "v1" }, "v2" }
是错误的,因为您(非const)引用了一个临时文件。
因此,您有悬而未决的参考文献。
我建议删除允许临时绑定到非const引用的扩展名。