gpt4 book ai didi

c++ - 类继承 : static members and virtual methods

转载 作者:行者123 更新时间:2023-11-28 02:19:23 25 4
gpt4 key购买 nike

我正在制作一个异常类,它只是在 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 的一般要点?

最佳答案

这是一个示例,它减少了对象占用空间并将内存分配从 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)
{ }
};

关于c++ - 类继承 : static members and virtual methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com