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

标签 c++ oop inheritance virtual-functions

我正在制作一个异常类,它只是在 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/

相关文章:

python - 父类中的 self.__dict__ 字典没有子属性?

c# - 如何使用单例进行继承

c++虚拟关键字与覆盖函数

perl - 为什么 perl 打印文件句柄语法是这样的?

JavaScript 多重继承和 instanceof

oop - R : Use a different base field/corpus 中的运算符重载和类定义

c++ - 在函数中更改类实例的值

c++ - Linux 64bit 调用约定使用寄存器传递 'this' 指针,但代码效率较低?

c++ - 将启用 MPICH2 的代码转换为 OpenCL 代码

c++ - 在 C++20 中增加一个 volatile 并弃用对 volatile 的操作