2013-05-13 62 views
8

例如:如何從std :: runtime_error繼承?

#include <stdexcept> 
class A { }; 
class err : public A, public std::runtime_error("") { }; 
int main() { 
    err x; 
    return 0; 
} 

隨着("")runtime_error後,我得到:

error: expected '{' before '(' token 
error: expected unqualified-id before string constant 
error: expected ')' before string constant 

其他(沒有(""))我得到

In constructor 'err::err()': 
error: no matching function for call to 'std::runtime_error::runtime_error()' 

什麼錯?

(你可以在這裏進行測試:http://www.compileonline.com/compile_cpp_online.php

回答

13

這是正確的語法:

class err : public A, public std::runtime_error 

而不是:

class err : public A, public std::runtime_error("") 

正如你在上面幹什麼。如果你想要一個空字符串傳遞到std::runtime_error構造,這樣來做:

class err : public A, public std::runtime_error 
{ 
public: 
    err() : std::runtime_error("") { } 
//  ^^^^^^^^^^^^^^^^^^^^^^^^ 
}; 

這裏是一個live example顯示代碼編譯。

+1

我在http://www.compileonline.com/compile_cpp_online.php上試過了,你的建議給了我'沒有匹配函數調用'std :: runtime_error :: runtime_error()'' – mchen 2013-05-13 00:08:16

+0

@MiloChen:Are你確定你正確地複製了一切嗎?我添加了一個鏈接,顯示代碼編譯正確的示例 – 2013-05-13 00:09:39

+1

哦,我明白了,如果我錯過了構造函數err():std :: runtime_error(「」){}',它將不會編譯。這不是我*想*傳遞一個空字符串 - 我*強制*。 – mchen 2013-05-13 00:11:40