这是一个计算 cpp 代码的简单矩形区域,我对此有一些疑问:
#include <iostream>
#include <conio.h>
using namespace std;
class CRectangle
{
int *width, *heigth;
public:
CRectangle(int, int);
~CRectangle();
int area() { return (*width * *heigth);}
};
CRectangle :: CRectangle(int a, int b)
{
width = new int;
heigth = new int;
*width = a;
*heigth = b;
}
CRectangle :: ~CRectangle()
{
delete width;
delete heigth;
}
void main()
{
CRectangle rect1(3,4), rect2(5,6);
cout << "rect1 area = " << rect1.area() << "\n";
cout << "rect2 area = " << rect2.area();
getch();
}
- 为什么在这样的面向对象的代码中我们使用指针,我的意思是有什么好处?
- 在创建对象
rect1(3,4)
之后的这段代码中,我们创建了rect2(5,6)
,这样做,逻辑上(我认为)5 和在 width 和 height 指向的内存部分中替换了 6 而不是 3 和 4,因此 3 和 4 不再可用,但它们是。
请解释到底发生了什么?
最佳答案
1-why in such object oriented codes we use pointers,I mean what's the advantage(s)?
没有。
2, 3 and 4
与
width = new int;
heigth = new int;
您总是在每个构造函数调用中保留新 单独的内存位置。每个对象都有单独的宽度和高度内存位置,因此不会被覆盖。
但是,有一种情况是两个对象将共享相同的内存位置 - 如果您使用复制构造函数或赋值运算符将一个对象复制到另一个对象:
CRectangle rect1(3,4);
CRectangle rect2 = rect1;
CRectangle rect3(4, 5);
rect3 = rect1;
在这种情况下,width
和 height
获得与 rect1
相同的值,这将使所有三个对象都指向相同的内存位置。在 rect2
的情况下,不会调用默认构造函数,因此不会分配新内存,在 rect3
的情况下,width 的旧值
和 height
将丢失,并且变量将使用 rect1
中的内存位置进行更新,这将导致内存泄漏(因为内存分配在rect3
的默认构造函数永远不会被释放)。
关于c++ - 关于 "new"运算符的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663235/