0

我不确定这个问题是否合适,但我会尽我所能。如何在继承类中没有构造函数时抛出异常?

这是我的家庭作业的问题。 如果两条线平行或平行,作业要求我抛出异常。

原代码由我的教授提供,我的工作是修改它,使其能够抛出异常。

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,我也可以创建这些类的目的是抛出异常。任何替代解决方案来实现这个?

+2

您发布的代码使用旧的'throw'规范。如果该函数不抛出任何内容,则考虑删除这些内容并使用新的和现代的'noexcept'说明符,否则就不会有任何其他内容。在你的情况,请告知你的教授不使用这个古老的技术更多的 – Rakete1111

+2

*教授告诉我们,不要修改头文件,只有.cpp文件可以体改* - 你的教授应该知道用户定义的异常应从'std :: exception'派生,即'class RuntimeException:public std :: exception {...};' – PaulMcKenzie

+0

@PaulMcKenzie为什么它们应该从'std :: exception'派生? – 0x499602D2

回答

5

因为你有一个异常说明,你可能只抛出EqualLinesParallelLines。这些异常类型没有默认构造函数(它们的基类型没有默认构造函数),并且没有其他构造函数。构建这些例外的唯一方法是复制现有的例外。在不修改标题或违反标准的情况下抛出这些例外是不可能的。我会咨询教授,这对我来说看起来是个错误。

一般来说,异常符是一个坏主意。 See this answer。他们实际上已被弃用。

+0

许多同学已经与教授和助教咨询,但这里的是什么,他们告诉我们至今。 –

+1

他的任务有缺陷。你必须选择违反任务规则或语言规则。 –

+0

以下是TA所说的话:“由于经常被问到,下面是我可以提供的提示: 同样,两个继承的EqualLines和ParallelLines类是从超类RuntimeException派生的,当Tindell博士对代码发表评论时,所有你需要的成员变量和成员函数(包括构造函数)是从超类RuntimeException继承的,因为EqualLines和ParallelLine的主体都是空白的,换句话说,无论超类具有哪些功能,这两个继承类都具有它们全部“。 –