-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のコンストラクターは、1 つのパラメーター ( へのポインター) を取りますRectangle

new Rectangle(10,20)

newこの式はクラスのインスタンスを構築Rectangleし、クラス インスタンスへのポインターを提供しnewます。

そう:

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

クラスの新しいインスタンスへのポインターを取得した後、そのポインターは、クラスのインスタンスの のコンストラクターにRectangle渡されます。WindownewWindow

于 2016-07-11T12:14:44.240 に答える