是否可以在 C++ 中的另一个构造函数的参数中直接构造一个对象?

Is it possible to construct an object directly in the arguments of another constructor in c++?

我是 c++ 的新手,想知道是否可以这样做:

Rectangle rect(Point(0, 0), 10, 10); // doesn't work

想法是 Rectangle 采用 Point 对象以及宽度和高度参数。构造函数如下所示:

Rectangle::Rectangle(Point & point, double width, double height) {
  this->point = point;
  this->width = width;
  this->height = height;
};

Point::Point(double x, double y) {
  this->x = x;
  this->y = y;
};

我这样做可以得到想要的效果:

Point point(0, 0);
Rectangle rect(point, 10, 10); // this works

但我认为,如果我可以直接在新矩形的参数中实例化我的点,那就太好了。如果可能的话,请告诉我!谢谢!

这取决于Rectangle是如何定义的。

我假设它看起来像这样:

class Rectangle {
    Point point;
    double width, height;
    /*...*/
};

在这种情况下,像这样定义构造函数将起作用:

Rectangle::Rectangle(Point const& p, double w, double h) {
    point = p;
    width = w;
    height = h;
}

这将允许它采用临时值(如您所愿)或采用左值(这是您的第二个示例所做的)。

如果 Rectangle 是为了存储一个 引用 到一个点,那几乎可以肯定是一个设计错误,你应该改变它。

您可以在参数列表中实例化,但在构造函数之外您将无法使用 Point。该点将是构造函数的本地点。

之后您可以以 rect.point 的身份访问该点。

编辑:

由于您尝试使用指向点的引用,因此这将不起作用。

a "regular" 引用不能绑定到一个临时的,只能绑定常量引用 (const T&) 和 r-value-reference (T&&)

在您的第一个代码段中,Point(0, 0) 是临时的,因此不能绑定到 Point&,但在您的第二个代码段中,Point point(0, 0); 不是临时的,因此它有效。

在这种情况下,由于您不尝试修改临时文件,因此将其绑定到常量引用:

Rectangle::Rectangle(const Point & point, double width, double height)