2015-10-11 24 views
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的一般要點?

+1

這可能屬於上[代碼審查](http://codereview.stackexchange.com/)。 – 0x499602D2

+1

給你的'Exception'類(可能是'protected')構造函數,它接收'text'和'code'的值。然後通過派生類中的初始化程序列表調用構造函數。 – 0x499602D2

回答

2

下面是一個例子,即減少對象足跡和從擲子句移動存儲器分配程:

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) 
    { } 
};