为什么会出现此编译器错误?

Why is this compiler error happening?

我正在为一个用 C++ 编写的软件进行异常处理。我遇到编译器错误(使用 g++ (GCC) 4.8.1 / mingw32)我不明白,这是一个最小的例子:

#include <iostream>
#include <exception>

class Bad_Img_Load: public std::exception {
    //public:
    virtual const char* what() const throw(){
        return "An image could not be loaded.";
    }
};

int main () {
    try{
        throw Bad_Img_Load();
    }catch (Bad_Img_Load& e){
        std::cout << e.what() << '\n';
    }
    return 0;
}

错误是:

a.cpp: In function 'int main()':
a.cpp:6:22: error: 'virtual const char* Bad_Img_Load::what() const' is private
  virtual const char* what() const throw(){
                      ^
a.cpp:15:25: error: within this context
     std::cout << e.what() << '\n';
                         ^

请注意,如果我取消对 'public:' 行的注释,那么它就可以正常工作。但是它所继承的class'exception'将一切都定义为public。所以我完全不明白为什么会出现这个错误。

基本上只有一件事使 structclass 不同,那就是默认可见性。对于 struct,默认值为 public,对于 class,默认值为 private

谁告诉你 class 有默认的 public 可见性是错误的。任何初学者教科书都会告诉你同样的事情。

您要继承的 class 是否拥有它的所有成员 public 并不重要。如果您使用(在您的代码中隐式指定的)私有访问说明符重载继承的 class' public 函数,则重载是私有的。从技术上讲,您可以说您也在重载访问说明符。