二。设计一个直线类line(设直线方程为ax+by+c=0),其中包含三个数据成员a,b,c,一个显示数据成员的disp成员函数
和一个求两直线交点的友元函数setpoint,要求考虑当两直线平行或交点坐标的绝对值大于等于10^8时,可抛出异常信息,并进行相应的处理。实现代码如下:
#include<iostream> #include<cmath> using namespace std; class line{ private: double a,b,c; public: line(){//默认构造函数 a=1; b=1; c=1; } line(line &ob){//拷贝构造函数 a=ob.a; b=ob.b; c=ob.c; } void set(){ cout<<"输入a,b,c的值:"; cin>>a>>b>>c; try{ if(a==0&&b==0) throw 1; } catch(int){ cout<<"发生异常:无法构成直线方程"<<endl; } } void display(){ cout<<"a = "<<a<<endl; cout<<"b = "<<b<<endl; cout<<"c = "<<c<<endl<<endl; } friend void setpoint(line &ob1,line &ob2){ double x,y; try{ if(ob1.a/ob2.a==ob1.b/ob2.b&&ob1.a/ob2.a==ob1.c/ob2.c) throw 'a';//char if(ob1.a/ob2.a==ob1.b/ob2.b&&ob1.a/ob2.a!=ob1.c/ob2.c) throw 1;//int x=(ob1.c*ob2.b-ob2.c*ob1.b)/(ob2.a*ob1.b-ob1.a*ob2.b); y=(ob1.c*ob2.a-ob2.c*ob1.a)/(ob2.b*ob1.a-ob1.b*ob2.a); if(fabs(x)>=pow(10,8)||fabs(y)>=pow(10,8)) throw "交点坐标的绝对值大于等于10^8";//const char * cout<<"交点坐标:("<<x<<","<<y<<")"<<endl; } catch(int){ cout<<"发生异常:两直线平行"<<endl; } catch(char){ cout<<"发生异常:两直线重合"<<endl; } catch(const char *){ cout<<"交点坐标的绝对值大于等于10^8"<<endl; } } }; int main(void){ line ob1,ob2; ob1.set(); ob1.display(); ob2.set(); ob2.display(); setpoint(ob1,ob2); }
知识点:
C++ 异常处理
异常是程序在执行期间产生的问题。C++ 异常是指在程序运行时发生的特殊情况,比如尝试除以零的操作。
异常提供了一种转移程序控制权的方式。C++ 异常处理涉及到三个关键字:try、catch、throw。
- throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
- catch: 在您想要处理问题的地方,通过异常处理程序捕获异常。catch 关键字用于捕获异常。
- try: try 块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。