0
我正在一個異常類,簡單地報告了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;
成爲繼承類的特定靜態變量。或者,我可以用= 0
使方法void generate();
成爲純虛函數,這是我的第一個想法。
我的問題是:是否有可能使這個解決方案成爲一個更好的OOP示例和/或我是否忽略了OOD的一般要點?
這可能屬於上[代碼審查](http://codereview.stackexchange.com/)。 – 0x499602D2
給你的'Exception'類(可能是'protected')構造函數,它接收'text'和'code'的值。然後通過派生類中的初始化程序列表調用構造函數。 – 0x499602D2