0

次のコードがあります。

#include <exception>

class Exception : public std::exception {
private:
    const char* MESSAGE = "Exception"

public:
    inline virtual const char* what() const throw() {
        return this->MESSAGE;
    }
};

class ShoulderROMException : public Exception {
private:
    typedef Exception super;
    const char* MESSAGE = "ShoulderROM exception";

protected:
    static const int MAX_MESSAGE_LENGTH = 200;
    mutable char composedMessage[ShoulderROMException::MAX_MESSAGE_LENGTH];

public:
    virtual const char* what() const throw() {
        strcpy(this->composedMessage, super::what());
        strcat(this->composedMessage, " -> ");
        strcat(this->composedMessage, this->MESSAGE);
        return this->composedMessage;
    }
};

class KinectInitFailedException : public ShoulderROMException {
private:
    typedef ShoulderROMException super;
    const char* MESSAGE = "Kinect initialization failed."

public:
    virtual const char* what() const throw() {
        strcpy(this->composedMessage, super::what());
        strcat(this->composedMessage, " -> ");
        strcat(this->composedMessage, this->MESSAGE);
        return this->composedMessage;
    }
};

これにより、次のようなログ エントリが生成 されますException -> ShoulderROM exception -> Kinect initialization failed.

誰かがここで私を助けてくれたら、本当にいいですね。:)

よろしく、リロ

4

2 に答える 2

1

共通クラスを介して実装します。私はあなたのコードを次のように書き直します:

class Exception : public std::exception {
    static const char* MESSAGE = "Exception"
    static const int MAX_MESSAGE_LENGTH = 200;
    mutable char composedMessage[MAX_MESSAGE_LENGTH];

public:
    virtual const char* name() const throw() {
        return MESSAGE;
    }

    virtual const char* what() const throw() {
        strcpy(this->composedMessage, name());
        strcat(this->composedMessage, " -> ");
        strcat(this->composedMessage, this->MESSAGE);
        return this->composedMessage;
    }
};

class ShoulderROMException : public Exception {
    static const char* MESSAGE = "ShoulderROM exception";
public:    
    virtual const char* name() const throw() {
        return MESSAGE;
    }
};

class KinectInitFailedException : public ShoulderROMException {
    static const char* MESSAGE = "Kinect initialization failed."
public:
    virtual const char* name() const throw() {
        return MESSAGE;
    }
};

クラスにそれほど多くの実装が必要ない場合は、との両方が継承Exceptionする別の実装を追加してください。ShoulderROMExceptionKinectInitFailedException

コードには他にも問題があります。MESSAGEメンバーは である必要がありstatic、文字列を処理する方法はあまりC++ らしくありません。また、仮想関数をインライン化しても意味がないことも付け加えておきます。

于 2015-12-09T11:27:02.010 に答える