题目描述 定义一个Cat类,其拥有静态数据成员numOfCats,记录已经创建的Cat对象的个体数目,静态数据成员numOfCatsGo,记录已经销毁的Cat对象的个体数目;静态成员函数getNumOfCats(bool IsConstruted),当IsConstruted为true时读取numOfCats,当IsConstruted为false时读取numOfCatsGo;数据私有成员weight,记录Cat对象的体重。 定义一个Boat类,其拥有数据私有成员weight,记录Boat对象的体重。 根
时间: 2023-07-16 18:15:12 浏览: 155
Nginx + Tomcat实现请求动态数据和请求静态资源的分离详解
据题目描述,可以定义如下的Cat类和Boat类:
```c++
class Cat {
private:
double weight;
static int numOfCats;
static int numOfCatsGo;
public:
Cat(double w) {
weight = w;
numOfCats++;
}
~Cat() {
numOfCatsGo++;
}
static int getNumOfCats(bool IsConstruted = true) {
return IsConstruted ? numOfCats : numOfCatsGo;
}
};
int Cat::numOfCats = 0;
int Cat::numOfCatsGo = 0;
class Boat {
private:
double weight;
public:
Boat(double w) {
weight = w;
}
void setWeight(double w) {
weight = w;
}
double getWeight() {
return weight;
}
};
```
在Cat类中,weight是一个私有数据成员,记录猫的体重。numOfCats和numOfCatsGo是静态数据成员,分别记录已经创建的猫对象个数和已经销毁的猫对象个数。getNumOfCats是一个静态成员函数,可以根据传递的参数IsConstruted来读取numOfCats或者numOfCatsGo的值。
在Boat类中,weight是一个私有数据成员,记录船的体重。定义了一个setWeight函数和一个getWeight函数,用来设置和获取船的体重。
可以通过以下代码进行测试:
```c++
int main() {
Cat c1(2.3), c2(3.1), c3(1.8);
Boat b1(120.5), b2(200.8);
cout << "Number of constructed cats: " << Cat::getNumOfCats() << endl;
cout << "Number of destructed cats: " << Cat::getNumOfCats(false) << endl;
cout << "Weight of boat 1: " << b1.getWeight() << endl;
b1.setWeight(150.2);
cout << "Weight of boat 1: " << b1.getWeight() << endl;
return 0;
}
```
输出结果为:
```
Number of constructed cats: 3
Number of destructed cats: 0
Weight of boat 1: 120.5
Weight of boat 1: 150.2
```
阅读全文