如何在继承的类中没有构造函数时引发异常
how to throw an exception when there is no constructor in the inherited class?
我不确定这个问题是否合适,但我会尽力而为。
这是我的作业问题。家庭作业要求我在两条线平行或相等时抛出异常。
原始代码由我的教授提供,我的工作是修改它以使其能够引发异常。
行.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文件。
行.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
,我也不能创建这些类的对象来抛出异常。有什么替代解决方案可以实现这一目标吗?
因为你有一个异常说明符,所以你只能抛出EqualLines
或ParallelLines
。这些异常类型没有默认构造函数(其基类型没有默认构造函数),也没有其他构造函数。构造这些异常中任何一个的唯一方法是复制现有异常。如果不修改标头或违反标准,就不可能抛出这些异常中的任何一个。我会咨询教授,这对我来说是一个错误。
通常,异常说明符是一个坏主意。看到这个答案。它们实际上已被弃用。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 如何编写带有异常的构造函数
- 从 C++ 中异常的构造函数引发异常
- 我正在尝试创建一个使用 c++ 中的参数包构造函数的异常类
- 稍后在构造函数中重新启动异常指令删除此指令
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 构造函数中引发的异常
- 如何捕获源自静态分配对象的构造函数的异常?
- 从构造函数内存泄漏引发异常
- 智能指针和构造函数异常
- 构造函数C++异常说明符
- boost::archive::text_iarchive构造函数异常
- C++堆栈对象的构造函数异常处理
- 默认构造函数C++异常不会引发吗?
- 当函数中静态变量的构造函数异常终止时会发生什么
- 在c++中,如果基类构造函数异常,则构造函数和析构函数的顺序可以是这样
- 如何捕获构造函数异常
- C++构造函数异常处理
- 捕获构造函数异常的RAII方法
- Std::unique_ptr::reset和构造函数异常