我有以下代码:
#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;
}
};
这会生成如下所示的日志条目:
异常 -> ShoulderROM 异常 -> Kinect 初始化失败。
这正是我想要的,但我想避免明显的代码重复并且似乎无法找到一种(优雅的)方法来做到这一点。
如果有人能在这里帮助我,那就太好了。 :)
最好的问候, 星际宝贝
最佳答案
通过普通类实现。我会像这样重写你的代码:
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
类中有太多实现,请添加另一个 ShoulderROMException
和 KinectInitFailedException
都将继承的类。
您的代码还有其他问题:MESSAGE
成员应该是static
,并且您处理字符串的方式不是C++ish。我还要补充一点,内联虚函数没有任何意义。
关于c++ - 如何在不重复代码的情况下在子类中获取相同的方法代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176996/