2015-07-18 54 views
0

我想實現異常並將其從我的方法中拋出。預期在';'之前的主表達式令牌

這裏是h文件例外

#ifndef EXCEPTION_H 
#define EXCEPTION_H 

#include <exception> 
#include <string> 

namespace core { 

class no_implementation: public std::exception { 
private: 
    std::string error_message; 
public: 
    no_implementation(std::string error_message); 
    const char* what() const noexcept; 
}; 

typedef no_implementation noimp; 

} 

#endif 

這裏cpp文件

#include "../headers/exception.h" 

using namespace core; 

no_implementation::no_implementation(std::string error_message = "Not implemented!") { 
    this->error_message = error_message; 
} 

const char* no_implementation::what() const noexcept { 
    return this->error_message.c_str(); 
} 

這裏是方法

std::string IndexedObject::to_string() { 
    throw noimp; 
} 

但它讓我錯誤

throw noimp; //expected primary-expression before ';' token 

什麼問題?沒有你試着投類型,而不是一個對象的括號

throw noimp(); 

+0

應該是'throw no_implementation'? Ps在傳遞'std :: String'時使用'const'和引用 –

回答

6

要創建一個臨時的一個類型,你需要使用一個符號這樣的(注意額外的括號)。除非將默認值移動到聲明中,否則您還將指定該字符串:默認值在使用時需要可見。

2

首先,默認參數如std::string error_message = "Not implemented!"應該放在函數聲明中,而不是定義。也就是說,寫

... 
public: 
    no_implementation(std::string error_message = "Not implemented!"); 
... 

其次,你拋出值,而不是類型。你寫過throw noimp;,但noimp是一個類的名字。這應該可能是throw noimp();throw noimp("some message here");

相關問題