Tra*_* Su 0 c++ inheritance exception-specification runtimeexception
我不确定这个问题是否合适,但我会尽我所能.
这是我的作业问题.如果两条线平行或相等,则作业要求我抛出异常.
原始代码由我的教授提供,我的工作是修改它以使其能够抛出异常.
line.h
class RuntimeException{
private:
string errorMsg;
public:
RuntimeException(const string& err) { errorMsg = err; }
string getMessage() const { return errorMsg; }
};
class EqualLines: public RuntimeException{
public:
//empty
};
class ParallelLines: public RuntimeException{
public:
//empty
};
class Line{
public:
Line(double slope, double y_intercept): a(slope), b(y_intercept) {};
double intersect(const Line L) const throw(ParallelLines,
EqualLines);
//...getter and setter
private:
double a;
double b;
};
Run Code Online (Sandbox Code Playgroud)
教授告诉我们不要修改头文件,只能修改.cpp文件.
line.cpp
double Line::intersect(const Line L) const throw(ParallelLines,
EqualLines){
//below is my own code
if ((getSlope() == L.getSlope()) && (getIntercept() != L.getIntercept())) {
//then it is parallel, throw an exception
}
else if ((getSlope() == L.getSlope()) && (getIntercept() == L.getIntercept())) {
//then it is equal, throw an exception
}
else {
//return x coordinate of that point
return ((L.getIntercept()-getIntercept()) / (getSlope()-L.getSlope()));
}
//above is my own code
}
Run Code Online (Sandbox Code Playgroud)
因为那两个继承的类是空的,因此没有构造函数来初始化errorMsg,也没有我可以创建这些类的对象来抛出异常.实现这个的任何替代解决方案?