我不確定這個問題是否合適,但我會盡我所能。如何在繼承類中沒有構造函數時拋出異常?
這是我的家庭作業的問題。 如果兩條線平行或平行,作業要求我拋出異常。
原代碼由我的教授提供,我的工作是修改它,使其能夠拋出異常。
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