我想了解windows(新矩形(30,20))如何在下面的代码中工作

时间:2016-07-11 12:09:03

标签: c++ object-composition

所以我知道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;
}

1 个答案:

答案 0 :(得分:0)

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

new Rectangle(10,20)

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

所以:

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

获取指向Rectangle类的新实例的指针后,指针将传递给Window的构造函数,用于new类的Window实例