C++的类与异常类的使用与示范

参考:https://blog.csdn.net/qq_52345913/article/details/124308807

C++中类的使用

【描述】
声明并实现一个Cylinder类,表示圆柱体。Cylinder类包括:
double类型的私有数据成员radius和height,分别表示圆柱体底半径和高。
带默认参数的构造函数,将圆柱体底半径和高设置为给定的参数。半径和高的默认参数值为1。
访问器函数,分别用于访问圆柱体底半径和高。
成员函数computeVolume,返回圆柱体体积。
成员函数computeSurfaceArea,返回圆柱体表面积。
假设PI为3.14159。
【输入】
输入圆柱体的底半径和高。
【输出】
输出圆柱体的体积和表面积。
【输入示例】

4 8
【输出示例】

402.124
301.593
【来源】

《程序设计基础——以C++为例》第5章实验3。

#include <iostream>
using namespace std;
const double PI = 3.14159;
// 请在此处编写Cylinder类
class Cylinder {
private:
    double radius, height;
public:
    Cylinder() {
        radius = 1;
        height = 1;
    }
    Cylinder(double radius, double height) {
        this->radius = radius;
        this->height = height;
    }
    double getRadius() {
        return radius;
    }
    double getHeight() {
        return height;
    }
    double computeVolume() {
        return PI * radius * radius * height;
    }
    double computeSurfaceArea() {
        return 2 * PI * radius * (radius + height);
    }
};
int main() {
    double radius, height;
    cin >> radius >> height;
    Cylinder cylinder(radius, height);
    cout << cylinder.computeVolume() << endl;
    cout << cylinder.computeSurfaceArea() << endl;
    return 0;
}

C++中异常类的使用

【描述】
自定义异常类NegativeNumberException,表示对负数执行操作时出现的异常,如计算负数的平方根。该类有一个string类型的私有数据成员message,用来存放异常信息;一个无参(默认)构造函数和一个有参构造函数,用来设置异常信息;成员函数what,用来显示异常信息。在main函数中,让用户输入某个数,并调用squareRoot函数,计算该数的平方根。如果输入的是负数,squareRoot函数将抛出NegativeNumberException异常,否则返回该数的平方根。
【输入】
输入一个数。
【输出】
输出该数的平方根或者输出错误信息“Invalid argument!”。
【输入示例】

-8
【输出示例】

Invalid argument!
【来源】

《程序设计基础——以C++为例》第5章实验7。

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// 请在此处分别编写NegativeNumberException类和squareRoot函数
class NegativeNumberException {
private:
    string message;
public:
    NegativeNumberException() {
        message = "Exception";
    }
    NegativeNumberException(string message) {
        this->message = message;
    }
    string what() {
        return message;
    }
};
double squareRoot(double a) {
    double b;
    if(a<0)
    throw NegativeNumberException("Invalid argument!");
    else
        b = sqrt(a);
        return b;
}
int main() {
    double value;
    cin >> value;
    try {
        cout << squareRoot(value) << endl;
    }
    catch(NegativeNumberException &ex) {
        cout << ex.what() << endl;
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值