如何在没有代码重复的子类中获得相同的方法代码?

时间:2015-12-09 10:54:46

标签: c++ exception duplicates code-duplication generalization

我有以下代码:

std::initializer_list

这会生成如下所示的日志条目: #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; } }; 这正是我想要的,但我想避免显而易见的代码重复,并且似乎无法找到(优雅)方式。

如果有人可以帮助我,那会非常好。 :)

祝你好运, 星际

2 个答案:

答案 0 :(得分: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 ++ ish 。我还要补充一点,内联虚函数没有任何意义。

答案 1 :(得分:1)

感谢您的帮助。它让我受到启发。通过一个同学的一些额外的想法,我想出了这个解决方案,它很有效。 :)

Literal1.Text = yourSQLValue;

我从错误的一面看问题:自上而下而不是自下而上。 ^^

感谢您的帮助和最诚挚的问候, 星际