class Cat {
private:
double weight; // 私有数据成员
static int numOfCats; // 静态数据成员,记录已创建的Cat对象个数
static int numOfCatsGo; // 静态数据成员,记录已销毁的Cat对象个数
public:
Cat(double w = 0.0) : weight(w) { // 构造函数
numOfCats++; // 创建Cat对象时,numOfCats自增
}
~Cat() { // 析构函数
numOfCatsGo++; // 销毁Cat对象时,numOfCatsGo自增
}
static int getNumOfCats(bool IsConstructed) { // 静态成员函数,读取numOfCats或numOfCatsGo
if (IsConstructed) {
return numOfCats;
} else {
return numOfCatsGo;
}
}
friend double getTotalWeight(const Cat& cat, const Boat& boat); // 友元函数声明
};
int Cat::numOfCats = 0; // 静态变量初始化
int Cat::numOfCatsGo = 0; // 静态变量初始化
class Boat { private: double weight; // 私有数据成员 public: Boat(double w = 0.0) : weight(w) {} // 构造函数 friend double getTotalWeight(const Cat& cat, const Boat& boat); // 友元函数声明 }; double getTotalWeight(const Cat& cat, const Boat& boat) { return cat.weight + boat.weight; // 计算一个Cat对象和Boat对象的体重和并返回 }