所以我知道new
和delete
隐式调用构造函数,但我无法理解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;
}
答案 0 :(得分:0)
Window
的构造函数接受一个参数,一个指向Rectangle
的指针。
new Rectangle(10,20)
此表达式构造new
类的Rectangle
实例,为您提供指向new
类实例的指针。
所以:
Window *wRect = new Window(new Rectangle(10,20));
获取指向Rectangle
类的新实例的指针后,指针将传递给Window
的构造函数,用于new
类的Window
实例