Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 内部结构初始化Don';t工作-C++;_C++ - Fatal编程技术网

C++ 内部结构初始化Don';t工作-C++;

C++ 内部结构初始化Don';t工作-C++;,c++,C++,我正在尝试一个根本不起作用的代码。写入输出时,即使已初始化,颜色字符串也会变为空 #include <iostream> #include <string> #include <sstream> using namespace std; struct Shape { virtual string str() const = 0; }; struct Circle : Shape { Circle() = default; string st

我正在尝试一个根本不起作用的代码。写入输出时,即使已初始化,颜色字符串也会变为空

#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;
}
#包括
#包括
#包括
使用名称空间std;
结构形状{
虚拟字符串str()const=0;
};
结构圆:形状{
圆圈()=默认值;
字符串str()常量重写{
ostringstream oss;

oss
ColoredShape{ColoredShape{circle,“v1”},“v2”}
错误,因为您将(非常量)引用用于临时

所以你有悬而未决的参考


我建议删除允许将临时引用绑定到非常量引用的扩展。

它不是存储在堆栈中吗?所以只要主函数处于活动状态,它就不应该是一个真正的引用吗?@MeCe它在语句末尾被销毁。因此,为什么在执行语句后它会立即成为一个悬空引用。