(1) 原因是程序中定义的构造函数和析构函数只是对静态变量count进行了加减操作,并没有对实际的矩形对象进行统计。

(2) 修改后的程序如下:

#include using namespace std; class Rect { public: Rect() { count++; } Rect(const Rect& other) { count++; } ~Rect() { count--; } static int getCount() { return count; } private: int width; int height; static int count; }; int Rect::count=0; int main() { Rect rect1; cout<<"The count of Rect:"<<Rect::getCount()<<endl; Rect rect2(rect1); cout<<"The count of Rect:"<<Rect::getCount()<<endl; return 0; }

运行结果截图:

可以看到,已经创建了两个矩形对象,程序正确输出了矩形的数量为2

请阅读下列程序然后回答问题:#includeiostreamusing namespace std;class Rectpublic Rect count++; ~Rect count--; static int getCount return count; private int width; i

原文地址: https://www.cveoy.top/t/topic/cz4p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录