我正在爲正在開發的C++應用程序編寫一個小的層次結構的異常類,並且我無法間接從std::runtime_error
派生。這裏是代碼類似於什麼我至今寫:從沒有默認構造函數的虛擬基礎派生類
class RuntimeException : public virtual boost::exception, public virtual std::runtime_error {
public:
virtual ~RuntimeException() {}
RuntimeException() : runtime_error("A RuntimeException occurred.") {}
RuntimeException(const std::string& what) : runtime_error(what) {}
};
class IllegalArgumentException : public virtual RuntimeException {
public:
IllegalArgumentException() : RuntimeException("An IllegalArgumentException occurred.") {}
IllegalArgumentException(const std::string& what) : RuntimeException(what) {}
};
的RuntimeException
類編譯沒有問題,但IllegalArgumentException
拒絕彙編VS2015,生成錯誤:no default constructor exists for class "std::runtime_error"
爲IllegalArgumentException
兩個構造。這促使我C++繼承層次的瞭解,如我所料這段代碼編譯的罰款。
我的理解是,IllegalArgumentException
應該編譯,因爲,雖然這是事實,std::runtime_error
沒有默認的構造函數,它的構造是由構造爲RuntimeException
調用。但顯然這必須是錯誤的,因爲編譯器正在拒絕它。它似乎想我直接從IllegalArgumentException
構造函數調用std::runtime_error
構造函數(編譯錯誤消失,當我這樣做),但是這似乎是錯誤的,因爲這樣我會被要求std::runtime_error
構造器兩次:一次是在構造函數RuntimeException
,並再次在IllegalArgumentException
的構造函數中。
這是安全和/或有效的嗎?如果不是,編譯器爲什麼似乎鼓勵它呢?我可能只是從std::exception
派生並實現std::string
我自己作爲成員變量,但我認爲從已經實現了這一點的標準類派生將更容易。這是錯誤的方法嗎?此外,事實上,我從boost:exception
和std::runtime_error
幾乎都會導致這個問題?
謝謝你,你的解釋很清楚。鑑於此,我很可能最終會從'std :: exception'派生並使用我自己的'std :: string'。這似乎是最簡單的方法。 –