定义一个动物类,其中动物有数据成员身高、体重,并提供显示动物信息的成员函数, 如果用户忘记给动物身高或者体重信息,抛异常提醒用户
时间: 2023-06-16 19:07:15 浏览: 37
下面是一个动物类的代码实现,其中包含了身高和体重的数据成员,以及显示动物信息的成员函数。在构造函数中,如果用户没有传入身高或体重的参数,就会抛出自定义的异常提醒用户需要提供这些信息。
```cpp
#include <iostream>
class Animal {
public:
Animal(double h, double w) : height(h), weight(w) {
if (h <= 0 || w <= 0) {
throw std::invalid_argument("身高和体重必须大于0");
}
}
void showInfo() const {
std::cout << "身高:" << height << ",体重:" << weight << std::endl;
}
private:
double height;
double weight;
};
int main() {
try {
Animal animal1(1.2, 20.3);
animal1.showInfo();
Animal animal2(1.5, -2.0);
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
```
在上面的代码中,我们通过 `std::invalid_argument` 类实现了一个自定义的异常,并在构造函数中使用 `throw` 语句抛出这个异常。在 `main` 函数中,我们通过 `try-catch` 语句捕获了这个异常,并在 `catch` 块中输出了异常信息。如果用户没有提供正确的身高和体重信息,就会抛出这个异常并提醒用户重新提供信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)