我想了解窗口(新矩形(30, 20))在以下代码中是如何工作的

I wanted to understand how the windows(new rectangle(30, 20)) is working in following code

本文关键字:代码 何工作 工作 窗口 了解 新矩形      更新时间:2023-10-16

所以我知道newdelete隐式调用构造函数,但我无法弄清楚window(new rectangle (30, 20))是如何工作的。

#include <iostream>
using namespace std; 
class Rectangle
{    
     private:
         double height, width;
     public:
         Rectangle(double h, double w) {
             height = h;
             width = w;
         }
         double area() {
         cout << "Area of Rect. Window = ";
         return height*width;
         }
};
class Window 
{
    public: 
        Window(Rectangle *r) : rectangle(r){}
        double area() {
            return rectangle->area();
        }
    private:
        Rectangle *rectangle;
};

int main() 
{
    Window *wRect = new Window(new Rectangle(10,20));
    cout << wRect->area();
    return 0;
}

Window的构造函数接受一个参数,一个指向Rectangle的指针。

new Rectangle(10,20)

此表达式构造 Rectangle 类的new实例,为您提供指向new类实例的指针。

所以:

Window *wRect = new Window(new Rectangle(10,20));

在获得指向Rectangle类的新实例的指针后,指针将传递给Window的构造函数,以获取Window类的new实例。