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的主體都是空白的,換句話說,無論超類具有哪些功能,這兩個繼承類都具有它們全部「。 –