-2

私が試したこと:

class MyException : public std::runtime_error {};

throw MyException("Sorry out of bounds, should be between 0 and "+limit);

そのような機能をどのように実装できるかわかりません。

4

2 に答える 2

0

文字列を受け取り、それを std::runtime_error のコンストラクターに送信する MyException のコンストラクター関数を定義する必要があります。このようなもの:

class MyException : public std::runtime_error {
public:
    MyException(std::string str) : std::runtime_error(str)
    {
    }
};
于 2013-10-31T22:48:44.847 に答える
0

ここには 2 つの問題があります。例外で文字列パラメーターを受け入れる方法と、ランタイム情報から文字列を作成する方法です。

class MyException : public std::runtime_error 
{
    MyExcetion(const std::string& message) // pass by const reference, to avoid unnecessary copying
    :  std::runtime_error(message)
    {}          
};

次に、文字列引数を構築するさまざまな方法があります。

  1. std::to_string is most convenient, but is a C++11 function.

    throw MyException(std::string("Out of bounds, should be between 0 and ") 
                      + std::to_string(limit));
    
  2. Or use boost::lexical_cast (function name is a link).

    throw MyException(std::string("Out of bounds, should be between 0 and ")
                      + boost::lexical_cast<std::string>(limit));
    
  3. You could also create a C-string buffer and use a printf style command. std::snprintf would be preferred, but is also C++11.

    char buffer[24];
    int retval = std::sprintf(buffer, "%d", limit);  // not preferred
    // could check that retval is positive
    throw MyException(std::string("Out of bounds, should be between 0 and ")
                       + buffer);
    
于 2013-10-31T23:51:23.807 に答える