天天看點

linux 構造函數 throw,在自定義異常的方法/構造函數簽名中帶和不帶throw()的C++...

我是C++的初學者,是以對這個愚蠢的問題表示歉意。我在這裡釋出它,因為我無法在stackoverflow上找到類似的答案。在自定義異常的方法/構造函數簽名中帶和不帶throw()的C++

我是通過在C++和我正在做一些手與自定義異常例外進步,我有這樣的代碼

class MyException: public std::exception{

public:

virtual const char* what() const throw() {

return "something bad happened";

}

};

// class that throws above exception

class canGoWrong {

public:

canGoWrong(){

throw MyException();

}

};

上面的代碼被老師表示。構造函數剛剛實作了在基類exception中定義的虛函數。我到了那裡。

現在,當我嘗試使用不同的版本進行練習時,我嘗試使用自定義函數而不是重新定義虛拟(因為C++沒有嚴格執行接口的概念,如果我在這裡錯了,請糾正我的錯誤。)

我寫它作為

class my_custom_shit_exception: public std::exception {

public:

const char* show() { // I omitted the const throw() here

return "This is an error encountered\n";

}

};

class myclass {

public:

myclass() {

throw my_custom_shit_exception();

}

};

總之,我沒有發現這兩種方式在活動的差異

public:

const char* show() {

return "This is an error encountered\n";

}

virtual const char* what() const throw() {

return "something bad happened";

}

那麼為什麼在what()虛函數中使用const throw()?它有什麼不同?

謝謝大家。

+3

“因為C++沒有嚴格執行接口的概念”它的确适用于純虛函數,如果這就是你的意思。 –

+1

你省略的throw()是一個'異常說明'它告訴編譯器該函數不會抛出任何異常,'what()'函數即不說它強制執行。為了清楚起見,請閱讀異正常範。 –

+1

非常有趣的問題。這不是同一個問題,但我認為[這個是有幫助的](https://stackoverflow.com/questions/5230463/what-does-this-function-declaration-mean-in-c) –