我不确定这个问题是否合适,但我会尽我所能。如何在继承类中没有构造函数时抛出异常?
这是我的家庭作业的问题。 如果两条线平行或平行,作业要求我抛出异常。
原代码由我的教授提供,我的工作是修改它,使其能够抛出异常。
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;
};
教授告诉我们,不要修改头文件,只有.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
}
因为这两个继承的类都是空的,因此没有构造函数初始化errorMsg
,我也可以创建这些类的目的是抛出异常。任何替代解决方案来实现这个?
您发布的代码使用旧的'throw'规范。如果该函数不抛出任何内容,则考虑删除这些内容并使用新的和现代的'noexcept'说明符,否则就不会有任何其他内容。在你的情况,请告知你的教授不使用这个古老的技术更多的 – Rakete1111
*教授告诉我们,不要修改头文件,只有.cpp文件可以体改* - 你的教授应该知道用户定义的异常应从'std :: exception'派生,即'class RuntimeException:public std :: exception {...};' – PaulMcKenzie
@PaulMcKenzie为什么它们应该从'std :: exception'派生? – 0x499602D2