为下列代码添加一个静态数据成员count,用来统计已生成的长方体对象的个数。 #include <iostream> using namespace std; class Rectangle { private: double length; double width; public: Rectangle() { cout << "无参构造函数被调用" << endl; } Rectangle(double l, double w) : length(l), width(w) { cout << "带参数的构造函数被调用" << endl; } Rectangle(const Rectangle& r) { //拷贝构造函数 length = r.length; width = r.width; cout << "拷贝构造函数被调用" << endl; } ~Rectangle() { //析构函数 cout << "析构函数被调用" << endl; } void setLength(double l) { length = l; } void setWidth(double w) { width = w; } double getPerimeter() { return 2 * (length + width); } double getArea() { return length * width; } }; int main() { Rectangle r1(3, 4); Rectangle* pr = &r1; //通过指针访问r1对象 pr->setLength(5); pr->setWidth(6); cout << "长方形的周长为:" << pr->getPerimeter() << endl; cout << "长方形的面积为:" << pr->getArea() << endl; Rectangle rectangles[3]; for (int i = 0; i < 3; i++) { double l, w; cout << "请输入第" << i + 1 << "个长方形的长和宽:"; cin >> l >> w; rectangles[i].setLength(l); rectangles[i].setWidth(w); cout << "第" << i + 1 << "个长方形的周长为:" << rectangles[i].getPerimeter() << endl; } return 0; }
下面是添加静态数据成员count后的代码:
#include
class Rectangle { private: double length; double width; static int count; // 静态数据成员count用来统计已生成的长方体对象的个数 public: Rectangle() { count++; // 每次生成对象时,count加1 cout << "无参构造函数被调用" << endl; } Rectangle(double l, double w) : length(l), width(w) { count++; cout << "带参数的构造函数被调用" << endl; } Rectangle(const Rectangle& r) { //拷贝构造函数 length = r.length; width = r.width; count++; cout << "拷贝构造函数被调用" << endl; } ~Rectangle() { //析构函数 count--; cout << "析构函数被调用" << endl; } void setLength(double l) { length = l; } void setWidth(double w) { width = w; } double getPerimeter() { return 2 * (length + width); } double getArea() { return length * width; } static int getCount() { // 静态成员函数getCount用来返回已生成的长方体对象的个数 return count; } };
int Rectangle::count = 0; // 静态数据成员count初始化为0
int main() { Rectangle r1(3, 4); Rectangle* pr = &r1; //通过指针访问r1对象 pr->setLength(5); pr->setWidth(6); cout << "长方形的周长为:" << pr->getPerimeter() << endl; cout << "长方形的面积为:" << pr->getArea() << endl;
Rectangle rectangles[3];
for (int i = 0; i < 3; i++) {
double l, w;
cout << "请输入第" << i + 1 << "个长方形的长和宽:";
cin >> l >> w;
rectangles[i].setLength(l);
rectangles[i].setWidth(w);
cout << "第" << i + 1 << "个长方形的周长为:" << rectangles[i].getPerimeter() << endl;
}
cout << "已生成的长方形对象的个数为:" << Rectangle::getCount() << endl;
return 0;
}
相关推荐

















