我正在创建一个异常类,只是在cout
上报告问题并退出程序,如下所示:
class Exception {
protected:
short code;
string text;
public:
friend ostream& operator <<(ostream& out, const Exception& p_exception) {
return out << p_exception.text;
}
void execute() { cout << text; exit(code);
};
以及它的具体例子:
class IndexOutOfBoundsException : public Exception {
public:
IndexOutOfBoundsException() {
this->text = "\nERR: An unsuccessful attempt was made to access the index outside the bounds of the array!";
code = 1;
}
};
class IndexOfEmptyFieldException : public Exception {
public:
IndexOfEmptyFieldException() {
this->text = "\nERR: An unsuccessful attempt was made to access the index of an empty field!";
code = 2;
}
};
class AllocationFailureException : public Exception {
public:
AllocationFailureException() {
this->text = "\nERR: An unsuccessful attempt was made to allocate dynamic memory!";
code = 3;
}
};
在我的脑海里,这一切看起来都非常整洁,但现在它似乎并不是一个好的OOP例子。当我思考它时,我发现我可以以某种方式使用静态成员,比如使int code;
成为继承类特有的静态变量。或者,我可以使用void generate();
使方法= 0
成为纯虚函数,这是我的第一个想法。
我的问题是:是否有可能使此解决方案成为更好的OOP示例和/或我是否错过了OOD的一般要点?
答案 0 :(得分:2)
这是一个示例,它减少了对象占用空间并使内存分配远离throw子句:
class Exception {
protected:
short code;
const string &text;
Exception(short code, const string &text) :
code(code), text(text)
{}
...
}
class IndexOutOfBoundsException : public Exception {
private:
static const string c_text = "\nERR: An unsuccessful attempt was made to access the index outside the bounds of the array!";
public:
IndexOutOfBoundsException() : Exception(1, c_text)
{ }
};