-1

私はこのようなものを書くことができる方法を見つけようとしています:

try{
    throw MyCustomException;
}
catch(const MyCustomException &e){
cout<< e;
}

overloaded operator <<しかし、この目的のために を定義する方法は?

カスタム例外クラス:

class MyCustomException{

public:

MyCustomException(const int& x) {
    stringstream ss;
    ss << x; 

    msg_ = "Invalid index [" + ss.str() + "]";
}

string getMessage() const {
    return (msg_);
}
private:
    string msg_;
};
4

1 に答える 1

4

正直なところ、正しい解決策は、標準的な慣習に従いMyCustomException、派生元を作成することだと思いますstd::exception。次に、what()仮想メンバー関数を実装してメッセージを返し、最終的にその文字列を を介して標準出力に挿入できますoperator <<

例外クラスは次のようになります。

#include <string>
#include <sstream>
#include <stdexcept>

using std::string;
using std::stringstream;

class MyCustomException : public std::exception
{
public:

    MyCustomException(const int& x) {
        stringstream ss;
        ss << x;
        msg_ = "Invalid index [" + ss.str() + "]";
    }

    virtual const char* what() const noexcept {
        return (msg_.c_str());
    }

private:

    string msg_;
};

使用方法は次のとおりです。

#include <iostream>

using std::cout;

int main()
{
    try
    {
        throw MyCustomException(42);
    }
    catch(const MyCustomException &e)
    {
        cout << e.what();
    }
}

最後に、実際の例です。

于 2013-04-07T00:38:38.380 に答える