-2

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

1 回答 1

0

Window的构造函数有一个参数,一个指向 a 的指针Rectangle

new Rectangle(10,20)

这个表达式构造了一个类的new实例Rectangle,给你一个指向new类实例的指针。

所以:

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

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

于 2016-07-11T12:14:44.240 回答