我想了解窗口(新矩形(30, 20))在以下代码中是如何工作的
I wanted to understand how the windows(new rectangle(30, 20)) is working in following code
所以我知道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;
}
Window
的构造函数接受一个参数,一个指向Rectangle
的指针。
new Rectangle(10,20)
此表达式构造 Rectangle
类的new
实例,为您提供指向new
类实例的指针。
所以:
Window *wRect = new Window(new Rectangle(10,20));
在获得指向Rectangle
类的新实例的指针后,指针将传递给Window
的构造函数,以获取Window
类的new
实例。
相关文章:
- 不确定要在我的main中放入什么才能使我的代码正常工作
- C++代码停止工作错误使用cout内部函数
- 代码在Visual Studio 2017中不起作用,但在VS代码中工作
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- 试图弄清楚我需要做哪些更改才能使代码正常工作.使用Visual Studio
- 可视化的c++变量赋值使代码正常工作
- 类似的代码.一个工作,一个崩溃.为什么?
- 删除运算符如何在我的代码中工作
- 以下代码如何工作以及何时终止
- 当写和读在不同的文件中时,C++二进制读取会产生segfault,但放在一个文件中的相同代码可以工作
- 无法使我的代码正常工作
- 为什么这个C++代码可以工作?(可能很简单)
- 矢量在C++中,我的代码可以工作,但不是我想要的那样
- 有人可以向我解释该代码的工作原理吗?(Palindrome C )
- 此C 代码如何工作?非初始化的指针
- If和else-If语句.它是如何在下面的代码中工作的
- C++为什么这些代码能工作
- CPP MQTT Broker代码不工作
- 为什么这个C++代码的工作方式