继承的class没有构造函数怎么抛异常?

how to throw an exception when there is no constructor in the inherited class?

我不确定这个问题是否合适,但我会尽力而为。

这是我的作业题。 作业让我在两条线平行或相等时抛出异常。

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

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 ,我也不能创建那些 类 的对象来抛出异常。任何替代解决方案来实现这一目标?

因为你有一个异常说明符,所以你只能抛出EqualLinesParallelLines。这些异常类型没有默认构造函数(它们的基类型没有默认构造函数)并且没有其他构造函数。构造这些异常中的任何一个的唯一方法是复制一个现有的异常。如果不修改 headers 或违反标准,就不可能抛出这些异常。我会向教授咨询,我觉得这是一个错误。

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